androidiosflutterdartshake

How to detect a phone shake in Flutter?


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}'),
          ),
        );
      }
    }