what is the benefit behind provider or BLoC pattern?

Viewed 2771

We have a lot of State management solutions like providers and BLoC pattern. But, why do we need them?. why can't I create a file called 'data.dart' and import this file(data.dart) wherever i need, and make changes to the variables and objects in this file(data.dart)? Does this pattern has any downsides?

2 Answers

State management solutions are needed for datas that changes.

Imagine having data.dart file that has a variable

String text = 'abc';

And you have a Text() widget called TextA that takes in text variable as input. This widget would initially display abc

now you have this function called

void changeText(){
text = 'cba';
}

how would this function tell TextA to rebuild because the value of text has already been changed?

of course you can use setState((){}); as long as the function is part of TextA,

but what if the Widget is ButtonA?

similar to StatefulWidget you can change the value using setState() to rebuild the widgets but what if you want a button in child widget that change the value in parent widget ? here you need to use provider to get full control.

Note: this is as example but it has multiple uses. you can use it with Firebase auth or cloud Firestore.

Related