state management with provider

state management the big picture

state management is about rebuilding the widget when data change.

why ? because the widget is dump it can not rebuild it self if you don’t tell it to do that(unless you are using stream) , in other word it does not know the data is changed until you tell it to rebuild it self and show the new data.

that means for example when you press the button to sum tow numbers the result in text widget will not appear even the operation is done successfully (the logic is executing but the result does not showing or drawing on the ui) and this is what called stated management.

so the state management is about integration of data with ui .you can manage the state using many techniques the most simple one is SetState() using Statefull widget and you can change the data with SetState() method .

code taken from flutter official website here

there are a lot of techniques to manage state you can find here
here.

but in this article I’ll write about provider .

how it works ?

provider is holding your data and rebuild the widget when you call it and notify any related widget with this changes so they rebuild there selves and be updated with these new changes .
provider helps you to rebuild only (listener) widget and not all the tree
that so helpful for performance , instead of rebuild whole the tree it rebuild only specific widget .

lets list the steps of using provider in your app

to illustrate the steps I’ll use part of simple task management app

  1. add provider package to pubspec.yaml
    -get the latest version of the provider from here
    -open your pubspec.yaml file and add provider dependency
    -press ctrl+s.

2. extend ChangeNotifier or using mixins
ChangeNotifier a class in the Flutter SDK it provides change notification to its listeners. In other words, if something is a ChangeNotifier , you can subscribe to its changes. to do that we include notifyListeners() , so any changes in the model will tell all methods that subscribed to it to update there selves with the new data

3. wrap your widget tree or your app with ChangeNotifierProvider()
this step help you to provide the data and makes it callable

4. call the provider with:

  • Provider.of<model>(context).property
    this is useful when we need to change data without rebuild listeners widgets by using turning the lister property to false
    Provider.of<model>(context,listen: false).method()

-Consumer
whenever ChangeNotifierchanged and notifyListeners() is called the consumer rebuilds itself by calling widget’s builder .

theses are the simple steps to use provider state management technique in flutter application you can get more advance if you need , just check the official documentation on flutter website here or the package docs here .

so lazy to write bio ..