0

I have a payment due alert in my application. It opens up on init of homepage. What my objective is to open the alert only once when the app opens up. I don't want to show that alert again when the user comeback to home screen. How can I achieve this?.

Febin Johnson
  • 277
  • 1
  • 6
  • 21
  • Do you mean after the first installation of the app, or whenever the user launch the app? – adamu_fura Mar 23 '22 at 14:38
  • 1
    You'll probably have to rely on some sort of flag (I'd use a state management solution, i.e. Provider - to hold that type of value) that gets persisted throughout the duration of the app while it's running so it doesn't show again. When the user dismisses the Alert, you set the flag to false, and anytime you want to bring it up again you check against this value by pulling it out of the provider, and since it will be false it shouldn't show it again. – Roman Jaquez Mar 23 '22 at 14:45
  • @RomanJaquez i have written the code to check the validity on init. Won't that flag get overwrite if i came to the same screen? – Febin Johnson Mar 23 '22 at 15:02
  • No it wont because in Flutter the State gets stored in memory as a separate entity from the UI building logic and not overritten, regardless of the widgets rebuilding - that's the purpose of state management, where the state is "lifted". I can send you a quick sample if you want as a Gist. – Roman Jaquez Mar 23 '22 at 15:14

2 Answers2

0

You can make a separate class and create flag there like this:

class Management {
  static bool dialogAppeared = false;
}

and your initState would look something like this:

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

  void openDialog() {
    if (Management.dialogAppeared == false) {
      showDialog(context: context, builder: (context) => YourDialog())
          .then((value) => Management.dialogAppeared = true);
    }
  }
Muhammad Hussain
  • 966
  • 4
  • 15
0

I created this Gist that shows you the implementation I explained in the comment above, which will give you the following result.

enter image description here

You'll be persisting the value in a Provided service, where the value will be persisted regardless of whether the widget rebuilds, since the state has been lifted and separated from the UI building logic. Check out the Gist above and run it on DartPad and you'll see.

Roman Jaquez
  • 2,499
  • 1
  • 14
  • 7