Reputation: 1013
Say my app starts on PageA, I'm trying to navigate to PageB 2 seconds after it loads.
Here is what I've tried...
In PageA:
Future _sleepTwo() {
return new Future.delayed(const Duration(seconds: 2), () => "sleeping...");
}
@override
void initState() {
this._sleepTwo().then((res) {
Navigator.push(
context,
new MaterialPageRoute(
builder: (BuildContext context) => PageB(),
));
});
}
But this gives me the following error:
E/flutter (22949): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: Navigator operation requested with a context that does not include a Navigator.
E/flutter (22949): The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget.
I've looked everywhere but got nowhere.
I even tried wrapping everything in initState()
with a Future(() => {code here});
. But it didn't work.
Upvotes: 0
Views: 74
Reputation: 6865
You won't have a context if the page hasn't initialized. Insert the following code into your Widget build(BuildContext context)
method.
_sleepTwo().then((res) {
Navigator.push(
context,
new MaterialPageRoute(
builder: (BuildContext context) => PageB(),
));
});
Don't use the await
keyword if you want the PageA to still draw itself, and then after two seconds switch to PageB
Upvotes: 1