• 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()));
    }
  • 相关阅读:
    css笔记
    CSS基础
    HTML常用基础标签
    React-Native中列表SectionList学习
    React-Native中列表FlatList配合网络请求fetch学习
    React-Native选项卡(react-navigation)之createBottomTabNavigator学习
    React-Native导航条(react-navigation)之createStackNavigator学习
    iOS中touch事件传递(响应者链)
    ios中UIView和CALayer关系
    iOS中KVO使用理解
  • 原文地址:https://www.cnblogs.com/luoyihao/p/14922107.html
Copyright © 2020-2023  润新知