Make a Flutter alertdialog when the app open


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 ?


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 {
  _MyHomePageState createState() => _MyHomePageState();

class _MyHomePageState extends State<MyHomePage> {
  ShakeDetector detector;
  bool dialogOpened = true;

  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
        context: context,
        builder: (cxt) => AlertDialog(content: Text('shake to close')),
      ).then((_) => dialogOpened = false);

    detector = ShakeDetector.autoStart(
      onPhoneShake: () {
        if (dialogOpened) {

        detector = null;


  void dispose() {

  Widget build(BuildContext context) {...}

Also add shake_event: ^0.0.4 to dependecies in pubspec.yaml.

Answered By – Igor Kharakhordin

Answer Checked By – Marie Seifert (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *