【发布时间】:2020-03-05 21:37:14
【问题描述】:
所以我希望我的 Flutter 应用程序在应用程序打开后立即生成警报对话框,并在我摇晃手机时使其崩溃我该怎么做?
【问题讨论】:
标签: flutter shake flutter-alertdialog
所以我希望我的 Flutter 应用程序在应用程序打开后立即生成警报对话框,并在我摇晃手机时使其崩溃我该怎么做?
【问题讨论】:
标签: flutter shake flutter-alertdialog
我不会给你确切的解决方案,但我会尽力指导你。
showDialog 函数可让您打开模式对话框。
您可以在 StatefulWidget 的 State 中使用 initState 方法在开始时调用 showDialog(当您的页面首次构建时)。
有一个plugin 用于检测手机震动。
当你检测到抖动时,你应该检查对话框是否打开(可能存储一些标志),如果它打开,调用Navigator.of(context).pop();关闭它。
UPD:好的,解决方案来了:
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
ShakeDetector detector;
bool dialogOpened = true;
@override
void initState() {
WidgetsBinding.instance.addPostFrameCallback((_) {
showDialog(
context: context,
builder: (cxt) => AlertDialog(content: Text('shake to close')),
).then((_) => dialogOpened = false);
});
detector = ShakeDetector.autoStart(
onPhoneShake: () {
if (dialogOpened) {
Navigator.of(context).pop();
}
detector?.stopListening();
detector = null;
}
);
super.initState();
}
@override
void dispose() {
detector?.stopListening();
super.dispose();
}
@override
Widget build(BuildContext context) {...}
}
还将shake_event: ^0.0.4 添加到 pubspec.yaml 中的依赖项中。
【讨论】: