【问题标题】:Provider : Looking up a deactivated widget's ancestor is unsafe提供者:查找已停用小部件的祖先是不安全的
【发布时间】:2020-12-26 19:28:00
【问题描述】:

尝试从提供者那里获取值,它工作正常,但我收到以下错误。我在这里做错了什么?

  @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.

【问题讨论】:

    标签: flutter dart provider


    【解决方案1】:

    问题在于无法等待导航器调用。如果您需要在构建时导航到正确的页面,则创建一个没有返回类型的异步方法,然后在 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();
    }
    

    【讨论】:

      猜你喜欢
      • 2020-08-08
      • 2021-11-15
      • 2021-06-03
      • 2022-06-26
      • 2021-04-29
      • 2020-11-18
      • 2021-07-28
      • 1970-01-01
      • 2020-06-19
      相关资源
      最近更新 更多