@override
void initState() {
final Future<bool> is_initialized = IsInitialized();
if (is_initialized == false) {
GenerateDefaultPreferences();
Navigator.push(context, MaterialPageRoute(builder: (context) => LanguageSelection())); //?
} else {
SynchronizeDLIfSet();
}
}
This is in my stateless widget. How can I navigate inside an initState() in Flutter?
I am trying to make it navigate to LanguageSelection() if the app didn’t initialize before.
3
Answers
You cannot have initState method in Stateless widget.
The initState() is a method that is called when an object for your stateful widget is created and inserted inside the widget tree. It is basically the entry point for the Stateful Widgets. To sum up, your widget must be Stateful.
Further explanation and example:
https://www.geeksforgeeks.org/flutter-initstate/
To navigate inside an
initState()
method in Flutter, you need to make a few changes. First, you need to convert your widget to aStatefulWidget
to use theinitState()
method. Also, instead of usingNavigator.push()
directly insideinitState()
, we need to add a micro-delay. Here’s the corrected code with explanations: