What is State Management?
The state of an app is any data that exists in the memory when the app is running . This state is crucial to rebuild the UI . It may range from assets to variables whose change of value may affect the UI .
What does Provider do?
Provider is Google’s recommended way of handling an app’s state . It can be imported and used in the form of a package available at www.pub.dev .
Advantages of Provider
(1) Change of state across the app
(2) Low complexity
(3) Developer-friendly
Steps to Provider
(1) Install the package
(2) Import the package
(3) Declare the class name and the widget name inside ChangeNotifierProvider
(4) Put business logic or the values to be updated inside Change Notifier followed by notifyListeners() to listen for change
(5) Call the function to activate and view the state change inside a widget or class
Provider Implementation in Flutter (Dart)
import ‘package:flutter/material.dart’;
import ‘package:provider/provider.dart’;
void main() {
// Declare the class name and the widget name inside ChangeNotifierProvider
runApp( ChangeNotifierProvider(
create: (_) => CountNotifier(),
child: CounterApp(),),
);}
// logic or the values to be updated stay here
class CountNotifier with ChangeNotifier {
int _counter = 0;
int get counter => _counter;
void incrementCounter() {
// testing the value change in Log / Run using debugPrint()
debugPrint(“Incrementing and notifying”);
_counter++;
// using listeners to notify the change
notifyListeners();
}}
class CounterApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,),
home: MyHomePage(title: ‘CounterApp (Provider + ChangeNotifier)’),
);}}
class MyHomePage extends StatelessWidget {
final String title;
MyHomePage({Key? key, required this.title}) : super(key: key);
@override)
Widget build(BuildContext context) {
debugPrint(“Tishan builds Flutter Provider”);
return Scaffold(
appBar: AppBar( title: Text(this.title),),
body: Center( child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(‘Your number of clicks so far today is: ‘),
// updating and displaying the changed-value in a Text widget
Text(‘${context.watch<CountNotifier>().counter}’,
),],),),
floatingActionButton: FloatingActionButton(
onPressed: () => context.read<CountNotifier>().
incrementCounter(),
tooltip: ‘Increment’,
child: Icon(Icons.add),),
);}}
// One may display the state-change elsewhere in another widget similarly