Flutter : StateManagement

 Image for post 

State Management

If I have a widget, and I want to change its state from somewhere outside of that widget, either from another widget, or from the network, or a system call.

 

So let’s build a very simple app. It shows the pie chart, and there is a slider, All we want to do is change the state of the pie chart in response to something happening in the slider.

If we look at the very simplified widget tree,we have, basically, only three widgets —

Homepage

MyChart

MySlider

And my slider wants to change the state of my chart.


Image for post

So we do something that we call in any declarative framework lifting state up. So we lift state up using — my schedule

As soon as slider change —

  • Instead of going to my chart directly, it goes through my schedule. It asks for my schedule and tells it,
hey, you know what? I was tapped, and this value changed
  • My schedule is responsible for notifying its listener. So it notifies my chart,
hey, something changed, and my chart redraws
  • It then goes down to my slider as well and says,
hey, this thing actually changed, and then it changed to my slider
 
 

Different Flutter State Management Techniques

  1. Scoped Model

Image for post

2. Bloc


Image for post
BLoC

3. Provider

This is what we are going to discuss in brief !

provider | Flutter Package

English | Português A wrapper around InheritedWidget to make them easier to use and more reusable. By using provider…

Add this in your dependencies in Pubspec.yaml. This will automatically get the latest version of provider

provider : 

There are three components related to this Provider State Management that we need to understand —

ChangeNotifier.

ChangeNotifierProvider

Consumer

 

 

Change Notifier adds listening capabilities to my schedule. So now, we get add listener, remove listener, dispose. And hey, I can notify listeners when things change. Since we added a lifting state up. So we lift state up using my schedule

The Most Important thing is calling notifyListeners(), whenever you change the state data in ChangeNotifier. If you will not call this method, the state change would not reflect in the UI. The method notifyListeners() tells flutter to rebuild the screen which is using that ChangeNotifier.


 

Comments

Popular posts from this blog

Flutter: Exploring more widgets

Flutter: Everything is a widget

Food Delivery App 5 - Firebase Storage for Profile Picture