The argument type 'MyBloc' can't be assigned to the parameter type 'MyBloc Function(BuildContext)

Issue

I’m trying to add flutter_bloc to my flutter application. I have Home page and when click on a button in home page Need to Navigation to a different page. Navigation is working without any issue, But When Wrap the the component with a BlocProvider getting below wrror

The argument type ‘MyBloc’ can’t be assigned to the parameter type ‘MyBloc Function(BuildContext)’

This what I have tried so far

My Bloc

import 'package:flutter_bloc/flutter_bloc.dart';

enum MyEvent {increment, decrement}

class MyBloc extends Bloc<MyEvent, int> {
  MyBloc() : super(0);  

  @override
  Stream<int> mapEventToState(MyEvent event) async* {
    switch (event) {
      case MyEvent.increment:
        yield state + 1;
        break;
      case MyEvent.decrement:
        yield state - 1;
        break;
    }
  }
}

In home page I’m calling below function when click on button

  Future<void> _routeToTodayTasks() {
    return Navigator.push(
        context,
        MaterialPageRoute(
            builder: (BuildContext context) => BlocProvider<MyBloc>(
            create: MyBloc(),
            child: TodayTasks(),
          )));
  }

Could anyone tell me what is wrong with my code?
enter image description here

Solution

As the error message clearly states, the create argument in BlocProvider is accepting a function with syntax MyBloc Function(BuildContext), but instead you are returning an object of your MyBloc class directly.

So, returns the bloc object from a function like this:

 create: (context) => MyBloc(),

Answered By – krishnakumarcn

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *