【问题标题】:flutter Navigator in initState, not working在 initState 中颤动导航器,不工作
【发布时间】:2021-06-06 12:10:48
【问题描述】:

我有这样的代码来自互联网,我的不工作:

class _StartingAnimationState extends State<StartingAnimation>{

  @override
  void initState() {
  Future.delayed(Duration(seconds: 4),(){
    Navigator.push(context, MaterialPageRoute(builder: (context) {
      return mainWindow();
    }));
  });
super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: SizedBox(height: 300,width: 300, child: Lottie.asset("assets/lottie/login.json")),             
      );
  }
}

我收到错误:

[ERROR:flutter/lib/ui/ui_dart_state.cc(177)] 未处理的异常:使用不包含导航器的上下文请求导航器操作。

和

用于从 Navigator 推送或弹出路由的上下文必须是作为 Navigator 小部件后代的小部件的上下文。

我希望我的程序显示动画一段时间,然后导航到其他屏幕

【问题讨论】:

  • initState 在构建上下文之前被调用,因此 Navigator.of(context) 将不起作用。试试 didChangeDependencies。
  • 谢谢,我在第二个之前看到了,我改了

标签: flutter dart


【解决方案1】:

您不能在initState 中推送新路由。您如何注册可以运行函数的后帧回调。 在你的build 方法中,在return 语句之前:

WidgetsBinding.instance.addPostFrameCallback((_){
Future.delayed(Duration(seconds: 4),(){
    Navigator.push(context, MaterialPageRoute(builder: (context) {
      return mainWindow();
    }));
  });
});

return MaterialApp(
      home: SizedBox(height: 300,width: 300, child: Lottie.asset("assets/lottie/login.json")),
          //home: SizedBox(height: 300,width: 300, child: Lottie.asset("assets/lottie/login.json")),
      );

【讨论】:

  • 感谢您的回答和时间,我解决了我的问题
【解决方案2】:

我会为任何会找到这个问题的人找到答案

答案是:

我没有将 MaterialApp 放在我的主目录中:

runApp(MaterialApp(home: StartingAnimation()));

而且我在我的 initState 中也看到了错误:

@override
  void initState() {
    super.initState();
  Future.delayed(Duration(seconds: 4),(){
    Navigator.push(context, MaterialPageRoute(builder: (context) {
      return mainWindow();
    }));
  });
  }

【讨论】:

    【解决方案3】:

    为什么它不起作用?

    MaterialApp配置顶级Navigator按顺序搜索导航路线:

    1. 对于/ 路由,如果非空,则使用 home 属性。

    2. 否则,如果路由表有路由条目,则使用路由表。

    3. 否则,将调用onGenerateRoute(如果提供)。它应该返回一个 任何未由 home 和 routes 处理的 有效 路由的非空值。

    4. 最后,如果一切都失败了,onUnknownRoute 会被调用。

    这就是为什么没有遵循上述方法时会出现错误Unhandled Exception: Navigator operation requested with a context that does not include a Navigator.

    解决方案!!!

    用MaterialApp包裹StartingAnimation

    runApp(MaterialApp(home: StartingAnimation()));
    

    注意:只有在route小部件上完成导航时才会发生这种情况,如果在其他小部件/屏幕上完成导航,则不会发生,因为MaterialApp已经初始化,因为每个人都添加到顶部.

    【讨论】:

      猜你喜欢
      • 2018-10-11
      • 2019-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      • 1970-01-01
      • 1970-01-01
      • 2021-09-14
      相关资源
      最近更新 更多