mono0926 / bloc_provider

Provides bloc to descendant widget (O(1)), and the bloc is disposed appropriately by state that the bloc_provider holds internally.
https://pub.dev/packages/bloc_provider
MIT License
115 stars 17 forks source link

Cannot create BuildProvider inside screen #14

Closed ngocmanh1609 closed 4 years ago

ngocmanh1609 commented 4 years ago

Hi @mono0926 👋 Nice to meet you and thank for useful library that helped me so much in work. 😁

But I have a concern and I dont know if it's a bug. For example, I have an app with 2 screens: Splash screen and Login screen. When I define BlocProvider (LoginBloc) for LoginScreen, I cannot define it inside LoginScreen, and I must define it in route, otherwise Invalid arguments error will be raised Invalid argument(s): LoginBloc is not provided to LoginScreen. Context used for Bloc retrieval must be a descendant of BlocProvider.:

// success
(BuildContext context) => BlocProvider<LoginBloc>(
          creator: (_, _bag) => LoginBloc(),
          child: LoginScreen(),
// failed: inside LoginScreen
@override
  Widget build(BuildContext context) {
    return BlocProvider<LoginBloc>(
        creator: (_, _bag) => LoginBloc(),
        child: Scaffold(
          primary: true,
          appBar: EmptyAppBar(),
          body: _buildBody(),
        ));
  }

This is just a minor problem but I dont know if it can be fixed, thank you 😁

mono0926 commented 4 years ago

It is intended behavior of BlocProvider or its internal implementation InheritedWidget.

Former example is correct. You can also use BlocProvider.builder(), which offers builder: (context, bloc) {}. You can use the context to get BLoC , and you can use the bloc of course.

@override
  Widget build(BuildContext context) {
    return BlocProvider<LoginBloc>.builder(
        creator: (_, _bag) => LoginBloc(),
        builder: (context, bloc) => Scaffold(
          primary: true,
          appBar: EmptyAppBar(),
          body: _buildBody(),
        ));
  }
ngocmanh1609 commented 4 years ago

I seem to understand more about InheritedWidget and its context usage, sorry I just start learning Flutter recently and I found that your library is a good thing to combine with reactive programming (rxDart) 😅 Thanks for replying me @mono0926 🙏