A value of type 'Widget?' can't be assigned to a variable of type '_BlocProviderInherited<T>'

Viewed 139

So, my code:

Type _typeOf<T>() => T;

abstract class BlocBase {
  void dispose();
}

class BlocProvider<T extends BlocBase> extends StatefulWidget {
  BlocProvider({
    Key? key,
    required this.child,
    required this.bloc,
  }) : super(key: key);

  final Widget child;
  final T bloc;

  @override
  _BlocProviderState<T> createState() => _BlocProviderState<T>();

  static T of<T extends BlocBase>(BuildContext context) {
    final type = _typeOf<_BlocProviderInherited<T>>();
    _BlocProviderInherited<T> provider =
        context.getElementForInheritedWidgetOfExactType<type>()?.widget;
    return provider?.bloc;
  }
}

class _BlocProviderState<T extends BlocBase> extends State<BlocProvider<T>> {
  @override
  void dispose() {
    widget.bloc.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return new _BlocProviderInherited<T>(
      bloc: widget.bloc,
      child: widget.child,
    );
  }
}

class _BlocProviderInherited<T> extends InheritedWidget {
  _BlocProviderInherited({
    Key? key,
    required Widget child,
    required this.bloc,
  }) : super(key: key, child: child);

  final T bloc;

  @override
  bool updateShouldNotify(_BlocProviderInherited oldWidget) => false;
}

The offending line is this one:

_BlocProviderInherited<T> provider =
        context.getElementForInheritedWidgetOfExactType<type>()?.widget;

And throws the error:

A value of type 'Widget?' can't be assigned to a variable of type '_BlocProviderInherited<T>'.

Edit: Additionally, it is throwing an error on the next line:

return provider?.bloc;

Error:

A value of type 'T?' can't be returned from the method 'of' because it has a return type of 'T'.

This is previously working code from my published app that no longer works after upgrading flutter from a quite old version.

Anyone know what it wants from me?

Edit: Have included full code, as referenced functions were not previously shown.

1 Answers
_BlocProviderInherited<T> provider =
        context.getElementForInheritedWidgetOfExactType<type>()?.widget;

This line fails because the variable types don't match. A Widget? is not a _BlocProviderInherited<T>. My guess is that the extends InheritedWidget used to mean that _BlocProviderInherited<T> had a type of Widget, but now (based on the InheritedWidget documentation and the method documentation) that is not the case.

A value of type 'T?' can't be returned from the method 'of' because it has a return type of 'T'. This error is caused by trying to return a variable that can be null from a method that only returns non-null variables. Flutter has changed a lot between major releases, including adding null safety. To fix it, change that line to return provider!.bloc; or provide a default bloc after: return provider?.bloc ?? <default value here>. Either way the returned value won't be null.

Related