1

I want to show a dialog when a stateless widget is built for the first time in Flutter.

If I add that to the build method it will be shown every time the widget is rebuilt (which the developer can't control directly).

Alternatively I could make my widget stateful and show the dialog in the initState method but then my setState method would be empty and that feels suboptimal.

What is the best practice for this situation? I could for instance introduce a global boolean variable tracking if the dialog has been shown before.

Nguyen
  • 111
  • 3
  • `I could for instance introduce a global boolean variable tracking if the dialog has been shown before` i can't see anything wrong with this approach – a_local_nobody Jan 14 '21 at 18:45
  • Show the dialog after the build method completed. Check this out https://stackoverflow.com/a/50682918/4608334. – Vinoth Vino Jan 14 '21 at 18:48

2 Answers2

3

if you want to use a stateless widget then you can use the following code to call a function after build method called

use below code inside build method

WidgetsBinding.instance
        .addPostFrameCallback((_) => yourFunction());

and if you want to execute the function once then you should use shared_preferences to store the value as true or false

Use the following code if you need:

yourFunction() async {
  SharedPreferences _prefs = await SharedPreferences.getInstance();

  bool _isFirstTime = _prefs.getBool("isFirstTime") ?? false; // if isFirstTime is null it will return false

  if (_isFirstTime) {
    // your code

    // after code executed set value as true
    _prefs.setBool("isFirstTime", true);
  }
}
1

Stateful Widget (or Riverpod :) would be the answer here.

have your State have something like:

bool firstTime = true;

and in the build method, if (firstTime), show the dialog and return, and set firstTime to false.

Randal Schwartz
  • 39,428
  • 4
  • 43
  • 70