Flutter: What is the need of state management libraries when I can use global variables and use setState instead?

646

Solution 1

setState function call builds the entire widget again which is a performance issue. State management manages the state without building the entire widget. Also, If your data are used on multiple screen you have to pass that data around using arguments which is cumbersome. That's why we use state management libraries. Hope it answers the question.

Solution 2

Whenever you calling setState() function, your entire Stateful or Stateless Widget will rebuild again. It makes your application's performace to low level.

For Eg: You have a Stateless Widget like Following

Scaffold(
 body: Column(
  children: [
   Container(
    child: Text(SomeText);
   ),
   FlatButton(
    onPressed: (){
     seState({
      //change Text Function
     });
    }
   )
  ]
 )
)

Here, when you click button and its function is to change value of SomeText,Now these all code will rebuild and yes, its replace SomeText with new value. But it is not just changed it but it rebuild entire widget to change it.

Here Instead of setState() method, if you are using any state management libraries, then it will only change value of SomeText without affecting other widgets.

as a beginer You can try Provider

Solution 3

The problem with calling setState() is that, it will rebuild all the children, where u call it.

You can optimize it, with InheritedWidget. But, InheritedWidget gives you a boilerplate code.

So, it's always practical to use some state management library rather than maintaining InheritedWidgets.

Share:
646
Sahil
Author by

Sahil

Updated on December 29, 2022

Comments

  • Sahil
    Sahil over 1 year

    I understand that bloc pattern or getX would provide extra features other than just state management in flutter, but my main concern is why should I use bloc or getX or any other state management library instead of just using setState with global variables?

    I do also understand that if I update the value of a global variable from a child class and navigate back to the parent then it's state will not be updated but to overcome this issue, I just called the setState() of parent from the child class. Is there anything wrong with my approach and if yes then what?