Flutter:尝试使用InheritedWidget但获取空

Thi*_*tal 5 dart flutter

小部件层次结构 我正在调用的of功能InheritedWidget,但是当如上所示,当我的窗口小部件位于树的顶部时,我的函数将返回null。呼叫来自推送到导航器堆栈的页面,而不是该页面。有人知道为什么吗?我的InheritedWidget代码如下。

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);
}
Run Code Online (Sandbox Code Playgroud)

Thi*_*tal 0

我通过将传递到 InheritedWidget 中的 MaterialPageRoute 的页面包装起来解决了这个问题。我假设树停在页面路由处并且不会到达更高的位置,尽管我不能 100% 确定。