4
votes

I am using initState and having Navigator issue:

I/flutter ( 5726): The following assertion was thrown building Builder: I/flutter ( 5726): setState() or markNeedsBuild() called during build.

My Code:

@override
void initState() {

super.initState();
print(globals.isLoggedIn);
if(globals.isLoggedIn) {

    print("Already login");

    Navigator.push(context, MaterialPageRoute(builder: (context)=> Dashboard()));

}
2
Also note that user will be able to return from Dashboard to previous page by pressing back buttonPavel

2 Answers

19
votes

We are getting the error as while building the Widget itself we are asking to navigate.

There is a work around for this.

Future(() {
   Navigator.push(context, MaterialPageRoute(builder: (context)=> Dashboard()));
});

Explaination:

As Dart is based on single-threaded event loop, when we create an async tasks, it will put those events in the end of the event queue and continue it's current execution. Please refer below example for more details,

void main() {
  print("first");
  Future(() => print("second"));
  print("third");
  Future(() => print("forth"));
}

Output will be

first
third
second
forth
-1
votes

Embedding the 'MyApp' inside the MaterialApp widget has solved the problem for me.

void main() {
runApp(MaterialApp(
home:MyApp()
));
}