So I want my Flutter app to make an alertdialog as soon as the app opens and make it collapse when I shake the mobile how can I make it ?
Asked
Active
Viewed 1,214 times
1 Answers
0
I won't give you the exact solution, but I'll try to guide you.
showDialog function lets you open a modal dialog.
You can use initState method inside State of StatefulWidget to call showDialog on start (when your page is being build for the first time).
There's a plugin for detecting phone shake.
When you detect a shake, you should check whether dialog is opened or not (probably store some flag) and if it is opened, call Navigator.of(context).pop();
to close it.
UPD: ok here comes the solution:
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) {...}
}
Also add shake_event: ^0.0.4
to dependecies in pubspec.yaml.

Igor Kharakhordin
- 9,185
- 3
- 40
- 39
-
I can't figure out why u won't give me the exact solution for my problem i know most of the components that u mentioned and tried so much before i ask here but nothing themed right so i came here to ask for a solution – Mohamed Eldereny Nov 14 '19 at 17:51
-
@MohamedEldereny Because your question looks like you haven't tried anything at all, that's why it's getting downvoted. Though what you want to implement isn't so hard to do. – Igor Kharakhordin Nov 15 '19 at 01:29
-
@MohamedEldereny Ok, here comes the solution. Please, upvote/accept the answer, if it helped you. – Igor Kharakhordin Nov 15 '19 at 14:34