Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to use InheritedWidget but Getting Null

Tags:

flutter

dart

Widget Hierarchy

I’m invoking the of function of the InheritedWidget, but my function is returning null when, as you can see above, I have my widget at the top of the tree. The call is coming from a page that was pushed onto the Navigator stack, which is not this page. Anyone know why? My InheritedWidget code is below.

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);
}
like image 670
ThinkDigital Avatar asked Aug 07 '18 01:08

ThinkDigital


1 Answers

InheritedWidget, in my testing atleast, can be inherited even if it's a parent of the MaterialApp/WidgetsApp/CupertinoApp or route.

For anyone else having this problem, a more likely explaination is that you've imported the InheritedWidget with different casing. i.e. Where you generate it, you may have imported it as import 'MyInheritedWidget.dart', while where you are trying to retrieve it, you have it imported as import 'myinheritedwidget.dart' .

This wont cause an error in either file (in windows atleast), but it will not be matched and return null.

like image 114
MSwehli Avatar answered Oct 20 '22 21:10

MSwehli