Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 449
Steve Kim Avatar asked Nov 14 '19 20:11

Steve Kim


Video Answer


2 Answers

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.

like image 72
Jack Avatar answered Oct 17 '22 07:10

Jack


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.

like image 33
thisisyusub Avatar answered Oct 17 '22 06:10

thisisyusub