Reputation: 696
I am trying to navigate to a page after a specific duration. However, whenever i run the app, i receive an error saying: At this point the state of the widget's element tree is no longer stable. To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling inheritFromWidgetOfExactType() in the widget's didChangeDependencies() method.
My code looks like this:
@override
void initState() {
super.initState();
googleSignIn.signInSilently(suppressErrors: false)
.then((account) async {
if (account != null) {
List<Post> posts = await initTimelinePosts(account.id);
List<String> followingList = await configureTimelineForNoPost(
account.id
);
currentUser =
User.fromDocument(await usersRef.document(account.id).get());
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => Home(
posts: posts,
followingList: followingList,
savedState: widget.savedState
)
)
);
} else {
Navigator.pushReplacement(
context,
MaterialPageRoute(
settings: RouteSettings(name: Auth.route),
builder: (context) => Auth(savedState: widget.savedState)
)
);
}
}).catchError((_) async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
String userId = prefs.getString('userId');
if (userId != null && userId.isNotEmpty) {
DocumentSnapshot doc = await usersRef.document(userId).get();
currentUser = User.fromDocument(doc);
List<Post> posts = await initTimelinePosts(userId);
List<String> followingList = await configureTimelineForNoPost(userId);
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => Home(
posts: posts,
followingList: followingList,
savedState: widget.savedState,
)
)
);
} else {
_timer = new Timer(
Duration(milliseconds: 3000),
() {
Navigator.pushReplacement( // the error message points to this line
context,
MaterialPageRoute(
settings: RouteSettings(name: Auth.route),
builder: (context) => Auth(savedState: widget.savedState)
)
);
}
);
}
});
}
I expect the app to run without errors but it doesn't. How do I solve this?
Note: I seriously don't know what to write anymore and SO keeps complaining that i need to add some more details. I believe i've provided enough explanation with the description, the title, and the code.
Upvotes: 0
Views: 1007
Reputation: 2229
I think the problem is that you are trying to navigate to a new page and replace this page in your initState(). Because the widget tree is not built when you run initState() method, it might cause an error.
Have a look at this answer for detailed explanation and this for a similar issue.
Upvotes: 1