Search code examples
flutterdartstatelessbloc

Flutter State Management (BloC): Stateless vs Stateful widget


So I am reading through Bloc for state management for flutter.

Since Bloc allows you to sink and stream (rebuilding a widget based on the input), then is it possible to build an app mostly with stateless widgets?

As an example, let say I make lots of single stateless class widgets, thus almost everything is compartmentalized into its own stateless widget.

With the Bloc state management, I could simply rebuild a certain stateless child widget to reflect the change.

In this approach, I don't see the need of using the stateful widget. Of course, being a total beginner in flutter, I wanted to hear if this approach has any merit to it.

Is this a good approach? Any info will be much appreciated.


Solution

  • You're right that you can use only StatelessWidgets. You just need to be cognizant of where you create your bloc. Some ways of instantiation are more easily testable than others, like passing the bloc to your StatelessWidget as an argument.

    But for implementation, I like the flutter_bloc library the best: https://pub.dev/packages/flutter_bloc

    It includes BlocProvider which automatically handles creation and disposal of blocs.

    One other thing to note is that you'll often have to kick off an event in a bloc to perform some action and a StatefulWidget could be useful to run that in the initState method.

    You could either say in a StatefulWidget:

    initState(){
       _myBloc = SomeBloc()..add(SomeEvent());
    }
    
    // Then somewhere in your widget tree
    BlocProvider<MyBloc>(
      create: (context) => _myBloc,
      builder: (context, state) {},
    )
    

    OR, in your StatelessWidget:

    BlocProvider<MyBloc>(
      create: (context) => MyBloc()..add(SomeEvent()),
      builder: (context, state) {},
    )
    

    You'll find what works best for you, but I've found with Flutter that it mostly depends on the situation and goal of a particular feature. There's no need to pin yourself into a habit of always needing to use a StatelessWidget, but you are right that it is possible.