dart – Flutter:尝试使用InheritedWidget但是获取Null

《dart – Flutter:尝试使用InheritedWidget但是获取Null》

我正在调用InheritedWidget的函数,但是我的函数返回null,如上所示,我将我的小部件放在树的顶部.该调用来自一个被推入Navigator堆栈的页面,该页面不是此页面.谁知道为什么?我的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);
}

最佳答案 我通过在InheritedWidget中包装传递给MaterialPageRoute的页面解决了这个问题.我假设树停在页面路线并且没有达到更高,尽管我不是100%肯定.

点赞