Search code examples
flutterdartproviderbloc

how to integrat bloc pattern with a flutter app?


So recently I am trying to integrate bloc pattern inside my already built app I started at the login page where i have two textfields for gsm and password I add the bloc package to the yaml file and installed the plugin bloc Then started with gsm field creating a bloc for it Then i realized that for the password I need another bloc And if i dive into sign up page I may need four or five blocs Is that the normal behavior or it may affect the performance and smoothness of the app and is there a better way using the bloc pattern ... is it better to build the bloc pattern from scratch using streams and sinks I already tried this and also created a provider like below :

    class Provider extends InheritedWidget {
  final bloc = Bloc();

  Provider({Key key, Widget child}) : super(key: key, child: child);

  @override
  bool updateShouldNotify(_) => true;

  static Bloc of(BuildContext context) {
    return (context.dependOnInheritedWidgetOfExactType<Provider>() as Provider)
        .bloc;
  }
}

but stuck of how to add more than one bloc in order to make the app more modular and readable and if I need to create a provider for each bloc or not,any help on this side also ... thanks in advance


Solution

  • You don't need to create a provider for each bloc. Your Provider class is an InheritedWidget, so redundant use of it might cause performance issues. It's already possible to access all your blocs through a single Provider.

    Provider

    All blocs are in your Provider class:

    class Provider extends InheritedWidget {
      final gsmBloc = GsmBloc(); // Bloc 1
      final passwordBloc = PasswordBloc(); // Bloc 2
      // add more ...
    
      Provider({
        Key key,
        Widget child,
      }) : super(key: key, child: child);
    
      @override
      bool updateShouldNotify(_) => true;
    
      static Provider of(BuildContext context) {
        return context.dependOnInheritedWidgetOfExactType<Provider>()!;
      }
    }
    

    MyApp

    Initialize Provider in your first widget (or beforehand in case you want to access it here):

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Bloc Pattern',
          home: Provider(
            child: MyHomePage(),
          ),
        );
      }
    }
    

    MyHomePage

    Access your blocs through Provider using the nearest context:

    class MyHomePage extends StatefulWidget {
      @override
      Widget build(BuildContext context) {
        // Access your blocs through Provider
        final passwordBloc = Provider.of(context).passwordBloc;
    
        return Scaffold(
          appBar: AppBar('Flutter Bloc Pattern'),
          body: Center(
             child: Text('My Home Page'),
          ),
        );
      }
    }