首页 > 解决方案 > 在 Widget build() 之外调用 Navigator 会产生上下文错误

问题描述

所以我基本上是在尝试检查用户是否在我的颤振应用程序中看到了介绍页面。如果他们已经看过,我希望他们被引导到该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])))
            )
        )
    );
  }
}

标签: flutternavigation

解决方案


GET所以我通过使用颤振库解决了这个问题。链接:flutter 获取库

使用这个库,不需要上下文来在页面之间导航,因此它是一种从 Flutter 中的任何地方导航的完整证明方法。


推荐阅读