Education
Last updated onJul 25, 2024
Last updated onAug 25, 2024
Are you familiar with Flutter state management?
Flutter state management entails various tasks, such as calling your app's network function, installing networking libraries, parsing data, and updating it on the main UI thread. Handling this can be difficult if you are new to Flutter state management concepts.
Every developer takes a different approach to the same work because there is no one "perfect solution" for all use cases. However, the developer's choice, knowledge of that approach, and level of comfort with it all influence the efficiency of the work done.
This article looks into the Flutter Provider state management and how to use Provider state manager in your Flutter application.
So, before you start, make sure you understand the 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 Redux are Flutter's most common state management options.
Here let's discuss the Flutter Provider state management.
Also, know more about the popular Flutter state management packages in 2023.
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.
The Provider makes data values such as state model objects accessible to child widgets. The package works like a straightforward and user-friendly wrapper for the Inherited Widgets.
Inherited Widget is a widget that may send data down to its child widgets without having to send that data down each level of the widget tree directly. This makes it an excellent choice for handling app-wide states.
It offers a state management strategy for managing the allocation and disposal of resources.
The Flutter UI can move data down a widget tree from parent to child, where it can be used. It is effective till your app becomes more complex and massive.
Consider passing the data above where we intend to use it elsewhere in the tree. As a result, you only need to inject the data when it is required. That is where the Flutter Provider state management comes in.
Before using the provider state management in the Flutter app, we must first understand these basic concepts:
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 changed.
1 import 'package:flutter/material.dart'; 2 class CounterModel with ChangeNotifier { 3 int _counter = 0; 4 CounterModel(this._counter); 5 getCounter() => _counter; 6 setCounter() => _counter= counter; 7 void incrementCounter() { 8 _counter++; 9 notifyListeners(); 10 } 11 } 12
Simply put, ChangeNotifierProvider is a widget that delivers a ChangeNotifier instance. The code excerpt below will help you understand how it works.
1 class MyApp extends StatelessWidget { 2 @override 3 Widget build(BuildContext context) { 4 return MaterialApp( 5 theme: ThemeData( 6 primarySwatch: Colors.blue, 7 ), 8 home: ChangeNotifierProvider<CounterModel>( 9 builder: (_) => CounterModel(), 10 child: CounterModelView(), 11 ), 12 ); 13 } 14 } 15
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 used.
1 return Consumer<CounterModel>( 2 builder: (context, counterModel, child) { 3 return Text("the value of counter is : ${counterModel.counter}"); 4 }, 5 ); 6
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:
1 dependencies: 2 provider: ^5.0.0 3
To get a local copy of the package, run the pub get command.
1 flutter pub get 2
The next step is to build a new Material app in the main.dart file.
1 import 'package:flutter/material.dart'; 2 3 void main() => runApp(MyApp()); 4 5 class MyApp extends StatelessWidget { 6 @override 7 Widget build(BuildContext context) { 8 return MaterialApp( 9 title: 'Material App', 10 home: Scaffold( 11 appBar: AppBar( 12 title: Text('Material App Bar'), 13 ), 14 body: Center( 15 child: Container( 16 child: Text('Hello World'), 17 ), 18 ), 19 ), 20 ); 21 } 22 } 23
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 declared in the UserDetailsProvider class.
This class extends the ChangeNotifier class, which offers access to the notifyListeners function, which will be used 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.
This page declares everything about the app's current state:
1 class UserDetailsProvider extends ChangeNotifier { 2 TextEditingController nameController = TextEditingController(); 3 TextEditingController ageController = TextEditingController(); 4 int _age = 0; 5 String _userName = ''; 6 int get userAge => _age; 7 String get userName => _userName; 8 void updateAge(int age) { 9 _age = age; 10 notifyListeners(); 11 } 12 void updateName(String name) { 13 _userName = name; 14 notifyListeners(); 15 } 16 } 17
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 are exposed by the ChangeNotifierProvider: create and child. The created property accepts the class we declared, which extends ChangeNotifier, and links the class to the screen:
1 import 'package:flutter/material.dart'; 2 import 'package:provider/provider.dart'; 3 void main() => runApp( 4 ChangeNotifierProvider<UserDetailsProvider>( 5 create: (_) => UserDetailsProvider(), 6 child: MyApp(), 7 ), 8 ); 9 // ignore: use_key_in_widget_constructors 10 class MyApp extends StatelessWidget { 11 @override 12 Widget build(BuildContext context) { 13 return const MaterialApp( 14 title: 'Material App', 15 home: HomeScreen(), 16 ); 17 } 18 } 19
Now that the app is connected to the class that provides the state, any change in the state triggers a rebuild of the app's displays.
Here are the key advantages and disadvantages of Flutter Provider state management.
Let's see in which scenario we can use Provider state managers in your Flutter application. And also when not to use this.
Following are the best practices for using Flutter Provider state management.
State management is an essential component of any Flutter app. It is critical to select the appropriate state management library for your project based on its complexity and your degree of experience.
The Provider is an excellent choice for maintaining the state in your Flutter project since it is simple to use and versatile enough to manage both simple and complicated states. You may use it to ensure your app runs well and your users have a positive experience.
Are you worrying about managing your Flutter application states?
Well, if you are using DhiWise, stop bothering about using state managers in your Flutter app. This platform provides you with inbuilt support for the Provider, GetX, BLoC, Riverpod approach as well as the Stateless approach. So, managing the state with Flutter Builder is going to be easier than ever.
Find out more about DhiWise Flutter builder and sign up for free to start building your next app with DhiWise.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.