-1

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!!!!!!

Raffaelli L.C.
  • 5,237
  • 5
  • 11
  • 18

1 Answers1

0

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.

Hamza
  • 1,523
  • 15
  • 33
  • Thanks you very much!! I tried but when I shake it it prints 5 times the message, do you know how can I fix that? And it is possible to configure a lower o higher sensibility to the shake? – Raffaelli L.C. Sep 07 '20 at 01:06
  • Yes, you need to decrease the threshold value, try something like 30.0 – Hamza Sep 07 '20 at 09:02