State management in Flutter:When developing the front-end app, it is necessary to handle the responses to each event triggered by UI activity. Technically, we must manage the state of UI components that change due to end-user interaction.
While managing the UI state, you may need to divide the massive UI into multiple smaller components while maintaining good communication.
Furthermore, all UI components should always know the application’s state.
Flutter supports various state management strategies, with the default setState function being the most basic. Although it is easy to use, you can only partially rely on it.
Other variables to consider when designing a Flutter app include app complexity, scalability, and architecture. That is why you want a comprehensive and successful strategy to state management.
Provider, BLoC, and Getx , Riverpod are Flutter’s most common state management options.
Here let’s discuss the Flutter Provider state management.
What is Flutter Provider state management?
State management in Flutter:
The Provider is a state management solution that extends and simplifies Inherited Widgets. It is a versatile and powerful state manager that allows you to deliver data to any widget in your app. Also, it is fast and optimized to rebuild only the widgets that need to be updated.
Three essential components of Flutter Provider state management:
Before using the provider state management in the Flutter app, we must first understand these basic concepts:
- ChangeNotifier
- ChangeNotifierProvider
- Consumer
ChangeNotifier
ChangeNotifier is a class that notifies its listeners when something changes. It is a more straightforward method for a limited number of listeners. It notifies its listeners about changes to the model using the notifyListeners() method.
For example, let us create a class CounterModel that extends ChangeNotifier and has a function incrementCounter() that will increment the counter and tell its listeners about the changes using notifyListeners(), and the UI will be change.
import 'package:flutter/material.dart';
class CounterModel with ChangeNotifier {
int _counter = 0;
CounterModel(this._counter);
getCounter() => _counter;
setCounter() => _counter= counter;
void incrementCounter() {
_counter++;
notifyListeners();
}
}
ChangeNotifierProvider
Simply put, ChangeNotifierProvider is a widget that delivers a ChangeNotifier instance. The code excerpt below will help you understand how it works.
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: ChangeNotifierProvider<CounterModel>(
builder: (_) => CounterModel(),
child: CounterModelView(),
),
);
}
}
Consumer
It is a widget with a builder function that is used to build the UI based on model updates. The builder function will pass the context, counter, and child parameters. Context is the same as every other widget creation function. The CounterModel member that was noticed for change is the counter. For optimization, the third argument child is use.
return Consumer<CounterModel>(
builder: (context, counterModel, child) {
return Text("the value of counter is : ${counterModel.counter}");
},
);
Using Provider for state management in Flutter
To use Provider in your Flutter app, create a new project first, then add the following line to your pubspec.yaml file’s dependencies block:
dependencies:
provider: ^5.0.0
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Material App',
home: Scaffold(
appBar: AppBar(
title: Text('Material App Bar'),
),
body: Center(
child: Container(
child: Text('Hello World'),
),
),
),
);
}
}
Managing state data
Create a new class now that includes the state data needed for the application. Here we name it as ‘UserDetailsProvider’. All the methods dealing with handling the state in this case will be declare in the UserDetailsProvider class.
This class extends the ChangeNotifier class, which offers access to the notifyListeners function, which will be use to notify listening widgets to rebuild when the state changes.
We define name and age as the two controllers for our TextFormField. This class also declares the method for updating the user’s name and age based on input from the user.
class UserDetailsProvider extends ChangeNotifier {
TextEditingController nameController = TextEditingController();
TextEditingController ageController = TextEditingController();
int _age = 0;
String _userName = '';
int get userAge => _age;
String get userName => _userName;
void updateAge(int age) {
_age = age;
notifyListeners();
}
void updateName(String name) {
_userName = name;
notifyListeners();
}
}
Updating the state
After updating the name, we call the notifyListeners function, which notifies the listening widgets of a change in the state and, as a result, causes a rebuild of all relevant widgets.
Now that we have the UserDetailsProvider class (which manages the state), we must use ChangeNotifierProvider to connect the class to the screen. Now, in the runApp method of the main block, enclose the entire program in a ChangeNotifierProvider.
Two significant attributes is expose by the ChangeNotifierProvider: create and child
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() => runApp(
ChangeNotifierProvider<UserDetailsProvider>(
create: (_) => UserDetailsProvider(),
child: MyApp(),
),
);
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Material App',
home: HomeScreen(),
);
}
}
For More: To know about Flutter Bloc State Management
Leave a Reply