context.dependOnInheritedWidgetOfExactType<_ModelBindingScope>() returns null

Viewed 45

So, I'm trying to adapt the login page from the flutter example "Shrine", however, when using the Login page as is, I get a weird null value error.

I have not the slightest hint what I'm doing wrong here, and what I should change. Yes, I tried poking into it with the debugger, but I still have no clue.

The exact place the error seems to occur (I think) is here:

static GalleryOptions of(BuildContext context) {
  final scope =
      context.dependOnInheritedWidgetOfExactType<_ModelBindingScope>()!;
  return scope.modelBindingState.currentModel;
}

For those interested, the code is up on my GitHub: https://github.com/vguttmann/betterchips/tree/dev

So, what's going on here? How do I fix it? Why did it happen in the first place?

1 Answers

It's pretty clear from the code some of the widgets are trying to access GalleryOptions, which you have not provided, from their build contexts.

Look at the widget tree root of the original gallery app (main.dart), the entire app is wrapped in a ModelBinding widget with some pre-defined values:

@override
  Widget build(BuildContext context) {
    return ModelBinding(
      initialModel: GalleryOptions(
        themeMode: ThemeMode.system,
        textScaleFactor: systemTextScaleFactorOption,
        customTextDirection: CustomTextDirection.localeBased,
        locale: null,
        timeDilation: timeDilation,
        platform: defaultTargetPlatform,
        isTestMode: isTestMode,
      ),
      child: Builder(
        builder: (context) {

Some of the components you copied expect to have ModelBinding widget somewhere in their line of ancestors. Failing to find one, the function returns null, and since it's marked as non-nullable (bang operator following the expressing), it immediately throws a runtime error.

If you're new to flutter I would advise you simply copy what they've done and wrap the entire app (MaterialApp) with a ModelBinding widget.

Related