[Solved] Make a Flutter alertdialog when the app open


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.

3

solved Make a Flutter alertdialog when the app open