我尝试在特定时间段后导航到页面。但是,每当我运行该应用程序时,我都会收到一条错误消息: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.
我的代码如下:
@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)
)
);
}
);
}
});
}
我希望该应用程序可以正常运行,但不会。我该如何解决?
注意:我真的不知道该写些什么了,所以一直抱怨我需要添加更多细节。我相信我已经提供了足够的说明,标题和代码说明。
答案 0 :(得分:0)
我认为问题是您试图导航到新页面并在initState()中替换此页面。由于运行initState()方法时未构建窗口小部件树,因此可能会导致错误。
有关详细说明,请参见this answer,有关类似问题,请参见this。