首页 > 解决方案 > 首次加载后导航到额外的页面秒数

问题描述

假设我的应用程序在PageA上启动,我试图在加载后 2 秒导航到PageB 。

这是我尝试过的...

在页面 A 中:

Future _sleepTwo() {
  return new Future.delayed(const Duration(seconds: 2), () => "sleeping...");
}

@override
void initState() {
  this._sleepTwo().then((res) {
    Navigator.push(
        context,
        new MaterialPageRoute(
          builder: (BuildContext context) => PageB(),
        ));
  });
}

但这给了我以下错误:

E/flutter (22949): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: Navigator operation requested with a context that does not include a Navigator.
E/flutter (22949): 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.

我到处找,但一无所获。

我什至尝试initState()Future(() => {code here});. 但它没有用。

标签: flutterdart

解决方案


如果页面尚未初始化,您将没有上下文。将以下代码插入您的Widget build(BuildContext context)方法中。

_sleepTwo().then((res) {
  Navigator.push(
      context,
      new MaterialPageRoute(
        builder: (BuildContext context) => PageB(),
      ));
});

如果您希望 PageA 仍然绘制自己,请不要使用await关键字,然后在两秒钟后切换到 PageB


推荐阅读