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

Viewed 965

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?

4 Answers

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

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.

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.

I'm not very well versed with the performance of flutter, my concerns are more on maintainability:

  1. When a child is aware of the parent and vice versa there's too much happening on widgets and you'll fail to layer the abstraction and over the period of time become hard to reason about.

  2. In javascript, we follow the flux pattern which talks about top-down state flow: If your app state doesn't follow unidirectional flow it becomes cumbersome to understand in very little time.

  3. If the state logic is not lifted above, your components won't have a single source of truth if the same data needs to be accessed elsewhere.

Hope this makes sense.

Related