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
This is how I achieved this in a simple way:
Add https://pub.dev/packages/shared_preferences
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;
}
}
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.