简体   繁体   中英

Migrating my bloc app to null safety. error: 'AssignmentBloc' doesn't conform to the bound 'BlocBase<AssignmentState>' of the type parameter 'B'

I'm migrating my flutter app to null-safety and I get this error on my BlocProvider and BlocBuilder.

'AssignmentBloc' doesn't conform to the bound 'BlocBase<AssignmentState>' of the type parameter 'B'.
Try using a type that is or is a subclass of 'BlocBase<AssignmentState>'.

I've checked the solutions to similar problems and it seems to me like I've already done what they suggested. I may be missing something though and I need help, please.

The widget.

class _AssignmentScreenWidgetState extends State<_AssignmentScreenWidget> {
  AssignmentBloc? _bloc;
  bool assignmentAdd = false;

  @override
  void initState() {
    super.initState();
    _bloc = BlocProvider.of<AssignmentBloc>(context)
      ..add(FetchEvent(widget.courseId, widget.assignmentId));
  }

  final GlobalKey<AssignmentDraftWidgetState> assignmentDraftWidgetState =
      GlobalKey<AssignmentDraftWidgetState>();

  @override
  Widget build(BuildContext context) {
    return BlocListener<AssignmentBloc, AssignmentState>( // where the errors are
      bloc: _bloc,
      listener: (BuildContext context, AssignmentState state) {
        if (state is CacheWarningAssignmentState) {
          showDialog(
              context: context, builder: (context) => WarningLessonDialog());
        }
      },
      child: BlocBuilder<AssignmentBloc, AssignmentState>( // where the errors are
          builder: (context, state) {
        return Scaffold(
        ...


The bloc.

class AssignmentBloc extends Bloc<AssignmentEvent, AssignmentState?> {
  final AssignmentRepository _assignmentRepository;
  final CacheManager cacheManager;

  AssignmentBloc(this._assignmentRepository, this.cacheManager) : super(null);

  @override
  AssignmentState get initialState => InitialAssignmentState();
  ...

The state.

@immutable
abstract class AssignmentState {}

class InitialAssignmentState extends AssignmentState {}

class LoadedAssignmentState extends AssignmentState {
    final AssignmentResponse assignmentResponse;

    LoadedAssignmentState(this.assignmentResponse);
}

class ErrorAssignmentState extends AssignmentState {}
class CacheWarningAssignmentState extends AssignmentState {}

Please, all the help I can get is very appreciated.

You _bloc variable isn't actually nullable. It's just not available in the constructor.

So make it late instead of nullable:

late AssignmentBloc _bloc;

That should solve your problems down the road, because now the type parameter of your bloc is no longer AssignmentBloc? but a real AssignmentBloc .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM