State Management Approaches in Flutter

26/05/2021 9:53

Bartu Kaan Pideci, Mobilist

Flutter Undoubtedly, one of the most important issues when developing applications with state administrationis. There are many state management approaches that Flutter recommends on its official website.

Some of those setStateProviderblocMobxgetxGetIt such approaches. In this series, we will take a look at these approaches with different usage methods.

Flutter's famous counter Everyone knows the (counter) application. To briefly remind you, the first thing we encounter when we create and compile a Flutter project is Flutter. low level sees it as an approach setState It is an example counter application developed with this approach.

This counter app different state management approaches We will develop and examine the differences between them and try to talk about the benefits of these approaches.

Firstly, setState approach most popular state management one of the approaches Provider We will compare it with the package.

setState vs Provider

Firstly setState Let's examine the approach.
setState method only Stateful WidgetIt is a concept used in 's.class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State {
int _counter = 0;

void _incrementCounter() {
setState(() {
_counter++;
});
}@override
Widget build(BuildContext context) {
return scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.Ugh(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

As seen in the example _counter value of variable _incrementCounter() increases within the method and setSate change thanks to the method WidgetTreeWe report to our.void _incrementCounter() {
setState(() {
_counter++;
});
}

Floating Action Button'of onPressed in its property _incrementCounter method is being called. So the button every time we click setState method is called. setState The class in which the method is called build method triggers and appears on the application screen of our widget tree. rebuild It means And while this may be costly in terms of processing power, it is also not an approach we want in terms of state management.floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);

Instead of redrawing the entire widget tree just _counter holding variable text widgetInforming about this change Only A much more convenient and correct approach would be to redraw this widget.

So how?

The Provider package is a good approach that can help us at this point.

First, install the Provider package pubspec.yaml in our file dependencies We add it to the field dependencies:
flutter:
sdk:flutter
provider: ^4.3.3

ChangeNotifier
ChangeNotifier It is available in Flutter SDK and provides its listeners (listeners) change notification (change notification) is a simple class that provides In other words, if something is a ChangeNotifier , subscribe to its changes (subscribe) you can be. Provider also ChangeNotifier APPLICATION its state encapsulation It is a way.
In our counter application example, a ChangeNotifierin counter of variable manage your state we want. This way it extend We create a new class that says:class Counter extends ChangeNotifier{
int counter = 0;

void increment(){
counter++;
notifyListeners();
}
}

Yes counter Our class is ready, now we add this class to our widget tree. ChangeNotifierProvider with inject Let's.

Change Notifier Provider
ChangeNotifierProvider
, to his descendants ChangeNotifier It is the widget that provides the instance. Change Notifier ProviderWe put the on widgets that need access to it. class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Counter Provider',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: ChangeNotifierProvider (
create: (_) => Counter(), child: MyHomePage()),
);
}
}

As seen in the example MyHomePage() widget ChangeNotifierProvider wrapping with class counter class to our tree inject we did.

Now, MyHomePage in counter your class to variables and to the methods We have the opportunity to access.class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Counter App with Provider'),
),
body: Center(
child: Consumer (
builder: (context, counter, child) {
return Text(counter.counter.toString(),
style: Theme.Ugh(context).textTheme.headline4);
},
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
var counter = context.read ();
counter.increment();
},
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

Here consumer that we wrap with counter holding variable 'Text Widget'We see ours. consumer what we want to access while using type of model We should point out.

In this situation counter we want; For this reason consumer We write. If counterIf we do not specify , Provider The package cannot help us. Provider, depends on species and without the species it cannot know what we want.

Consumer Widget placing it as deep into our widget tree as possible is the best method (best practice). Instead of rebuilding a large part of the UI only changing the relevant widget provides.

setState From the sample counter application developed with different aspect stateless widget we used and counter containing the variable text widgetof consumer with we wrapped and on change, that is, instead of redrawing our entire widget tree every time the button is clicked, Text Widget We ensured that it was recreated.var providerCounter = context.read ();
providerCounter.increment();

This time 'onPressed property'one in providerCounter We defined the variable and created the one we created above. counter class read contained in incerement() We have reached our method.

If your goal is just a simple counter application Doing is a usage as in Flutter's demo example. meet your needs may be suitable for this.

However, the work is more complicated and to big projects When it comes to this kind of approach performance While it will cause losses, it also brings with it various problems.

And finally, we should point out that best state management method There is no such thing.

It can be selected according to the project needs and the competencies of the people who will work on the project. optimum There is a solution. We can't say either one is better than the other. Each of them becomes important in meeting our needs in our project. In short, the most accurate method is It is the method that best suits the team and the project.

In this article, I will tell you about various usage methods. From Provider package and setState Differences between method and I tried to talk about it briefly.

In the continuation of this series, the other state management methods I will try to explain.

See you in my next articles…

en_USEnglish