flutteraccelerometergyroscopeuiaccelerometersensors

How can I configure the sensors (Accelerometer or gyroscope) to do something when the user shakes or rotate the phone?


How can I configure the sensors (Accelerometer or gyroscope) to do something when the user shakes or rotate the phone?

I want to show a new string each time the user shakes the phone.

Also I need a button to start and finish the sensors "action". Thanks!!!!!!


Solution

  • Use flutter_shake_plugin and you can try something like this:

    import 'package:flutter/material.dart';
    import 'dart:async';
    import 'package:flutter/services.dart';
    import 'package:flutter_shake_plugin/flutter_shake_plugin.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatefulWidget {
      @override
      _MyAppState createState() => _MyAppState();
    }
    
    class _MyAppState extends State<MyApp> {
      FlutterShakePlugin _shakePlugin;
    
      @override
      void initState() {
        super.initState();
        _shakePlugin = FlutterShakePlugin(
          onPhoneShaken: (){
            //do stuff on phone shake
            print('phone shakes');
          },
        )..startListening();
      }
    
      @override
      void dispose() {
        super.dispose();
        _shakePlugin.stopListening();
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: const Text('Shake Plugin example app'),
            ),
          ),
        );
      }
    }
    
    

    If you want to see live example. Take a look at this link I've implemented in one of my apps.