Issue
i tried to get run the ShakeDetector in my Flutter app. I got a sample app here. Can somebody help me to fix the problem? This codesample below is from the shake.dart github example. I dont get it why it is not working.
import 'package:flutter/material.dart';
import 'package:shake/shake.dart';
void main() {
runApp(DemoPage());
}
class DemoPage extends StatefulWidget {
@override
_DemoPageState createState() => _DemoPageState();
}
var phoneShakes;
class _DemoPageState extends State<DemoPage> {
@override
void initState() {
super.initState();
ShakeDetector detector = ShakeDetector.autoStart(onPhoneShake: () {
print('shaking');
});
// To close: detector.stopListening();
// ShakeDetector.waitForStart() waits for user to call detector.startListening();
phoneShakes = detector.mShakeCount;
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: AppBar(
title: Text(phoneShakes.toString()),
),
);
}
}
Solution
It's because there was no call to setState
. Try this code:
class _DemoPageState extends State<DemoPage> {
late ShakeDetector _detector;
@override
void initState() {
super.initState();
_detector = ShakeDetector.autoStart(onPhoneShake: () {
setState(() {}); // Call setState every time phone shakes.
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text('Count: ${_detector.mShakeCount}'),
),
);
}
}
Answered By - CopsOnRoad
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.