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.


Solution 1: Randal Schwartz

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.


Solution 2: Aakash kondhalkar

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);
  }
}