摇一摇检测

 

 

import 'package:flutter/material.dart';
import 'package:sensors/sensors.dart';
import 'package:permission_handler/permission_handler.dart';
import 'dart:async';
import 'dart:math';

main()=>runApp(MaterialApp(
  home: MyApp(),
));


class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return MyAppState();
  }
}
class MyAppState extends State<MyApp> {
  int c = 0;
  bool isMove = false;
  bool permission = false;

  checkPermit()async{
    var permit = await PermissionHandler().checkPermissionStatus(PermissionGroup.sensors);
    if(permit != PermissionStatus.granted){
      await PermissionHandler().requestPermissions([PermissionGroup.sensors]);
    }else{
      permission = true;
    }
  }

  @override
  Widget build(BuildContext context) {
    if(!permission){
      checkPermit();
    }

    accelerometerEvents.listen((AccelerometerEvent v){
      var xx = sqrt(v.x*v.x + v.y*v.y + v.z*v.z);
      print('$xx');
      if(!isMove){
          if(xx>14.0){
            c = c + 1;
            isMove = true;
            setState(() {});
          }
      }else{
        if(xx<12){
          isMove = false;
        }
      }
    });
    return SafeArea(child: Scaffold(
      appBar: AppBar(),
      body: Container(child: Center(child: Text('Count: $c'),),),
    ));
  }
}

  

posted @ 2019-05-20 18:11  CrossPython  阅读(358)  评论(0编辑  收藏  举报