Show alert dialog on app main screen load automatically in flutter

后端 未结 5 1347
遇见更好的自我
遇见更好的自我 2020-12-08 22:09

I want to show alert dialog based on a condition. Not based on user interaction such as button press event.

If a flag is set in app state data alert dialog is shown

5条回答
  •  有刺的猬
    2020-12-08 22:52

    This is how I achieved this in a simple way:

    1. Add https://pub.dev/packages/shared_preferences

    2. Above the build method of your main screen (or any desired widget):

      Future checkFirstRun(BuildContext context) async {
       SharedPreferences prefs = await SharedPreferences.getInstance();
       bool isFirstRun = prefs.getBool('isFirstRun') ?? true;
      
       if (isFirstRun) {
         // Whatever you want to do, E.g. Navigator.push()
         prefs.setBool('isFirstRun', false);
       } else {
         return null;
       }
      }
      
    3. Then on your widget's initState:

      @override
      void initState() {
        super.initState();
        WidgetsBinding.instance.addPostFrameCallback((_) => checkFirstRun(context));
      }
      

    This ensures the function is run after the widget is built.

提交回复
热议问题