1

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

1
  • 1
    create accepts a function which returns a bloc, not an instance of bloc, so use (context)=> MyBloc(), May 25, 2021 at 7:55

1 Answer 1

2

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(),

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.