Flutter之摇一摇功能的实现

1.在pubspec.yaml引入插件

sensors: ^0.4.0+1

2.编写shake.dart,代码如下:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:sensors/sensors.dart';

class Shake extends StatefulWidget {
  @override
  _ShakeState createState() => _ShakeState();
}

class _ShakeState extends State<Shake> {
  /// 是否已经显示摇一摇弹窗。
  bool isShow = false;

  @override
  void initState() {
    accelerometerEvents.listen((AccelerometerEvent event) {
      // 摇一摇阀值,不同手机能达到的最大值不同,如某品牌手机只能达到20。
      int value = 20;
      if (event.x >= value ||
          event.x <= -value ||
          event.y >= value ||
          event.y <= -value ||
          event.z >= value ||
          event.z <= -value) {
        if (isShow == false) {
          isShow = true;
          showDialog<bool>(
            context: context,
            barrierDismissible: true,
            builder: (BuildContext context) {
              return CupertinoAlertDialog(
                title: Text('摇一摇'),
                content: Text('您摇动了屏幕'),
                actions: [
                  CupertinoDialogAction(
                    child: Text('确定'),
                    onPressed: () {
                      Navigator.of(context).pop(true);
                    },
                  ),
                ],
              );
            },
          ).then((onValue) {
            if (onValue != null) {
              // 点击确定后返回的业务逻辑。
            }
            isShow = false;
          });
        }
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('摇一摇'),
      ),
      body: Center(
        child: Text('请摇动手机'),
      ),
    );
  }
}

3.从其他页面跳转过去

void shake(){
  Navigator.of(context).push(MaterialPageRoute(builder: (_) => Shake()));
}

 

posted @ 2021-06-23 11:47  罗毅豪  阅读(538)  评论(0编辑  收藏  举报