Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BlocProvider.of() called with a context that does not contain a Bloc of type CLASS

Tags:

flutter

bloc

in flutter i just learn how can i use Bloc on applications and i want to try to implementing simple login with this feature. after implementing some class of bloc to using that on view

i get error when i try to use this code as

BlocProvider.of<LoginListingBloc>(context).dispatch(LoginEvent(loginInfoModel: testLogin));

inside RaisedButton

Error:

BlocProvider.of() called with a context that does not contain a Bloc of type LoginListingBloc.

My view :

class _HomePageState extends State<HomePage> {
  LoginListingBloc _loginListingBloc;

  @override
  void initState() {
    super.initState();
    _loginListingBloc =
        LoginListingBloc(loginRepository: widget.loginRepository);
  }

  ...
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      bloc: _loginListingBloc,
      child: Scaffold(
        appBar: AppBar(
            elevation: 5.0, title: Text('Sample Code', style: appBarTextStyle)),
        body: Center(
          child: RaisedButton(
              child: Text(
                'click here',
                style: defaultButtonStyle,
              ),
              onPressed: () {
                BlocProvider.of<LoginListingBloc>(context).dispatch(LoginEvent(loginInfoModel: testLogin));
              }),
        ),
      ),
    );
  }
}

LoginListingBloc class:

class LoginListingBloc extends Bloc<LoginListingEvent, LoginListingStates> {
  final LoginRepository loginRepository;

  LoginListingBloc({this.loginRepository});

  @override
  LoginListingStates get initialState => LoginUninitializedState();

  @override
  Stream<LoginListingStates> mapEventToState(
      LoginListingStates currentState, LoginListingEvent event) async* {
    if (event is LoginEvent) {
      yield LoginFetchingState();
      try {
        final loginInfo = await loginRepository.fetchLoginToPage(
            event.loginInfoModel.username, event.loginInfoModel.password);
        yield LoginFetchedState(userInfo: loginInfo);
      } catch (_) {
        yield LoginErrorState();
      }
    }
  }
}

and other classes if you want to see theme

AppApiProvider class:

class AppApiProvider {
  final successCode = 200;

  Future<UserInfo> fetchLoginToPage(String username, String password) async {
    final response = await http.get(Constants.url + "/api/v1/getPersons");
    final responseString = jsonDecode(response.body);
    if (response.statusCode == successCode) {
      print(responseString);
      return UserInfo.fromJson(responseString);
    } else {
      throw Exception('failed to get information');
    }
  }
}

LoginEvent:

class LoginEvent extends LoginListingEvent {
  final LoginInfoModel loginInfoModel;

  LoginEvent({@required this.loginInfoModel}) : assert(loginInfoModel != null);
}

LoginInfoModel:

class LoginInfoModel {
  String username;
  String password;

  LoginInfoModel({this.username, this.password});
}

final testLogin = LoginInfoModel(username:'exmaple',password:'text');
like image 316
DolDurma Avatar asked May 12 '19 08:05

DolDurma


People also ask

How do you use BlocProvider in Flutter?

It is used as a dependency injection (DI) widget so that a single instance of a Bloc or Cubit can be provided to multiple widgets within a subtree. BlocProvider( create: (BuildContext context) => BlocA(), child: ChildA(), ); It automatically handles closing the instance when used with Create.

What is Bloc event Flutter?

Event Bloc is an event-based implementation of the BLoC pattern, the recommended State Management Pattern for Flutter by Google! Event Bloc uses events and the provider package to simplify the state management process.


2 Answers

No need to access loginListingBloc from context since it exists in the current class and not up the widget tree.

change:

BlocProvider.of<LoginListingBloc>(context).dispatch(LoginEvent(loginInfoModel: testLogin));  

to:

_loginListingBloc.dispatch(LoginEvent(loginInfoModel: testLogin));
like image 103
nonybrighto Avatar answered Oct 20 '22 01:10

nonybrighto


For all others who come here for the error message: Make sure you always specify the types and don't omit them:

BlocProvider<YourBloc>(
    create: (context) => YourBloc()
    child: YourWidget()
);

and also for

BlocProvider.of<YourBloc>(context);
like image 30
luckyhandler Avatar answered Oct 19 '22 23:10

luckyhandler