skip to Main Content
@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


  1. @override
    void initState() {
      super.initState();
      final Future<bool> is_initialized = IsInitialized();
    
      is_initialized.then((value) {
        if (!value) {
          GenerateDefaultPreferences();
          WidgetsBinding.instance.addPostFrameCallback((_) {
            Navigator.push(context, MaterialPageRoute(builder: (context) => LanguageSelection()));
          });
        } else {
          SynchronizeDLIfSet();
        }
      });
    }
    
    Login or Signup to reply.
  2. 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/

    Login or Signup to reply.
  3. To navigate inside an initState() method in Flutter, you need to make a few changes. First, you need to convert your widget to a StatefulWidget to use the initState() method. Also, instead of using Navigator.push() directly inside initState(), we need to add a micro-delay. Here’s the corrected code with explanations:

    class YourWidget extends StatefulWidget {
      @override
      _YourWidgetState createState() => _YourWidgetState();
    }
    
    class _YourWidgetState extends State<YourWidget> {
      @override
      void initState() {
        super.initState();
        
        // Check if the app has been initialized
        IsInitialized().then((isInitialized) {
          if (!isInitialized) {
            // If not initialized, generate default preferences
            GenerateDefaultPreferences();
            
            // Add a micro-delay before navigation
            Future.microtask(() {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => LanguageSelection()),
              );
            });
          } else {
            // If initialized, perform synchronization
            SynchronizeDLIfSet();
          }
        });
      }
    
      @override
      Widget build(BuildContext context) {
        // Build your widget tree here
        return Scaffold(
          // ...
        );
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search