Flutter State Management (BloC): Stateless vs Stateful widget

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.


You can use only Stateless Widget. But there is one problem that you should close streams before the app is disposed of. It can be handled in two ways:

  1. First, you can use a Stateful widget and close streams of bloc in the dispose method of stateful.

  2. Using BlocProvider. In this case, Bloc Provider is a Stateful widget only. It closes streams automatically. Then you can use bloc using BlocProvider in Stateless Widget.

But it doesn't mean that we don't need stateful widgets. Stateful widgets are important in animation for example. Animation, text input or any local changes in the widget itself shouldn't be handled in bloc or other state management. it is the duty of widget itself.