5

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

}
curveball
  • 4,320
  • 15
  • 39
  • 49
Rahul Mishra
  • 4,263
  • 7
  • 32
  • 53
  • Also note that user will be able to return from Dashboard to previous page by pressing back button – Pavel Sep 25 '19 at 14:08

2 Answers2

27

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
Dinesh Balasubramanian
  • 20,532
  • 7
  • 64
  • 57
  • Great explanation! Really appreciated but still, I am getting a warning in the console... unhandled Exception: Navigator operation requested with a context that does not include a Navigator. – Chirag Chopra May 22 '20 at 12:16
  • I am also facing the same issue, did you found a solution to this issue? – basudev nayak Jan 16 '21 at 12:05
-3

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

void main() {
runApp(MaterialApp(
home:MyApp()
));
}
Yam
  • 1
  • 2