Rahul Mishra
Rahul Mishra

Reputation: 4583

Flutter initstate navigator is not working

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

}

Upvotes: 6

Views: 12016

Answers (2)

Yam
Yam

Reputation: 1

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

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

Upvotes: -3

Dinesh Balasubramanian
Dinesh Balasubramanian

Reputation: 21768

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

Upvotes: 27

Related Questions