尝试从提供程序获取值,效果很好,但出现以下错误。我在这里做错了什么?
@override
Widget build(BuildContext context) {
String route = Provider.of<User>(context) == null ? Router.LOGIN : Router.HOME;
Future.delayed(const Duration(seconds: 2), () => Navigator.pushReplacementNamed(context, route));
return Scaffold(........
错误
E/flutter (23058): [ERROR:flutter/shell/common/shell.cc(209)] Dart Error: Unhandled exception:
E/flutter (23058): Looking up a deactivated widget's ancestor is unsafe.
E/flutter (23058): At this point the state of the widget's element tree is no longer stable.
E/flutter (23058): To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.
答案 0 :(得分:0)
问题是无法等待导航器调用。如果您需要导航到正确的构建页面,则创建一个没有返回类型的异步方法,然后在initState中调用该方法。
_checkUserExistsAndNavigate() async {
String route = Provider.of<User>(context) == null ? Router.login : Router.home;
await Future.delayed(seconds: 2), () => Navigator.pushReplacementNamed(context, route);
}
@initState(() {
_checkUserExistsAndNavigate();
super.initState();
}