所以我基本上是在尝试检查用户是否在我的颤振应用程序中看到了介绍页面。如果他们已经看过,我希望他们被定向到Login()
页面。否则,我希望将它们定向到IntroScreen()
页面。
但是,我收到以下错误:Unhandled Exception: Navigator operation requested with a context that does not include a Navigator. E/flutter (13982): 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.
这是我的代码:
void main() => runApp(CheckSplash());
//check if the intro screen has already been seen
class CheckSplash extends StatefulWidget {
@override
_CheckSplashState createState() => _CheckSplashState();
}
class _CheckSplashState extends State<CheckSplash> {
bool _introseen=true;
Future checkIntroSeen() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
bool _introseen = (prefs.getBool('seen') ?? false);
if (_introseen) {
Navigator.of(context).pushReplacement(
new MaterialPageRoute(builder: (BuildContext context) => Login()));
} else {
//await prefs.setBool('seen', true);
Navigator.of(context).pushReplacement(
new MaterialPageRoute(builder: (BuildContext context) => new IntroScreen()));
}
}
@override
void initState() {
super.initState();
new Timer(new Duration(milliseconds: 200), () {
checkIntroSeen();
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: appTheme,
debugShowCheckedModeBanner: false,
home: Builder(
builder: (context) => Scaffold(
resizeToAvoidBottomPadding: false,
body: Center(child: CircularProgressIndicator(valueColor: new AlwaysStoppedAnimation<Color>(Colors.red[300])))
)
)
);
}
}
所以我通过使用颤振GET
库解决了这个问题。链接:颤振获取库
使用此库,不需要上下文即可在页面之间导航,因此它是从颤振中的任何位置导航的完整证明方法。
我尝试了最简单的方法。在上下文生成器之后为您的代码创建一个函数。然后,只需将上下文作为函数参数:
Widget build(BuildContext context) {
return ....(your code)
}
yourFunction(context) {
Navigator.pop(context);
Navigator.push(context, MaterialPageRoute(builder: (context) => LoginScreen()));
}
它为我按预期工作。谢谢!
initState
内部的context
在SchedulerBinding.instance.addPostFrameCallback
中可用。此函数在构建小部件后触发。
@override
void initState() {
super.initState();
SchedulerBinding.instance.addPostFrameCallback((_) {
new Timer(new Duration(milliseconds: 200), () {
checkIntroSeen();
});
});
}