代码之家  ›  专栏  ›  技术社区  ›  ThinkDigital

Flatter:试图使用InheritedWidget,但得到空值

  •  5
  • ThinkDigital  · 技术社区  · 8 年前

    Widget Hierarchy

    我在调用 of 功能 InheritedWidget ,但我的函数返回null,正如您在上面看到的,我的小部件位于树的顶部。调用来自一个被推到导航器堆栈上的页面,而不是这个页面。有人知道为什么吗?我的 继承小部件 代码如下。

    class LiveKHProvider extends InheritedWidget {
      final LiveKHBloc liveKHBloc = LiveKHBloc();
    
      @override
      bool updateShouldNotify(InheritedWidget oldWidget) => oldWidget != this;
    
      static LiveKHBloc of(BuildContext context) {
        var inheritFromWidgetOfExactType =
            context.inheritFromWidgetOfExactType(LiveKHProvider); // to clearly see what’s returning null. 
            //This is where it returns null, 
            //so the below line is executed on a null object.
        return (inheritFromWidgetOfExactType as LiveKHProvider).liveKHBloc;
      }
    
      LiveKHProvider({Key key, Widget child}) : super(key: key, child: child);
    }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   MSwehli    7 年前

    至少在我的测试中,可以继承InheritedWidget,即使它是MaterialApp/WidgetsApp/CupertinoApp或route的父级。

    对于其他有此问题的人,更可能的解释是,您导入了具有不同大小写的InheritedWidget。i、 e.在您生成它的地方,您可能已经将其作为 import 'MyInheritedWidget.dart' ,当您试图检索它时,您将其作为 import 'myinheritedwidget.dart' .

    这不会在两个文件中(至少在windows中)导致错误,但它不会匹配并返回null。

        2
  •  0
  •   ThinkDigital    8 年前

    我通过在InheritedWidget中包装传递给MaterialPageRoute的页面解决了这个问题。我假设树在页面路径处停止,不会到达更高的位置,尽管我不是100%确定。