Sitemap
YavarTechWorks

Today a Reader, Tomorrow a Leader

Flutter — Provider

6 min readJan 17, 2024

--

State Management using Provider

Press enter or click to view image in full size

Welcome back, friends! In this journey, we’ll look into the Flutter Provider package for state management.

Through this Journey, we’ll see,

  1. Introduction to State Management
  2. Flutter State Management Tools
  3. Get — Into the Provider
  4. Usage with an Example
  5. Benefits for the users
  6. Finale

Before starting the journey, I wish to say something to you…

First of all, I’m requesting everyone to read this blog fully. And follow the step-by-step process to reach our destination!

Then only you'll be able to understand this concept.

Introduction to State Management:

Before we dive into the world of state management, let’s understand why it’s crucial to Flutter development.

App State:

  • In the context of mobile app development, ‘state’ refers to any data that can change over time.
  • This data can include user input, the content displayed on the screen, network responses, or even the device’s orientation.
  • For instance, think about a weather app. The location, temperature, and weather conditions are all examples of app state because they can change as the user interacts with the app or as new data arrives from an external source.

Importance of State Management:

  • Imagine building an app without any mechanism to handle the state. Every time something in your app changes, you need to manually update the user interface (UI) to reflect those changes.
  • This approach quickly becomes chaotic, error-prone, and unsustainable as your app grows in complexity.
  • This is where state management comes into play. It’s the practice of efficiently managing and updating the state of your application.
  • State management solutions provide structured ways to handle state changes and ensure that your app remains responsive and consistent.

Role Play:

  • Flutter is known for its impressive UI capabilities and robust performance. However, to make the most of Flutter’s potential, you need to manage your app’s state effectively.
  • Proper state management in Flutter involves handling everything from UI updates in response to user interactions to managing data fetched from APIs.
  • In a Flutter app, you’ll often find yourself needing to update the UI based on changes in the underlying data.
  • For example, when a user likes a post in a social media app, you need to update the UI to reflect the change in the number of likes. Without state management, this task can become convoluted.

To summarize, state management in Flutter is all about maintaining, updating, and synchronizing the data that your app relies on to function correctly. It’s the cornerstone of building responsive and dynamic user interfaces.

Flutter State Management Tools:

There are various state management approaches and packages available for Flutter. Here are some of the most popular ones:

  1. setState: The simplest form of state management built into Flutter. It’s suitable for small projects but can become cumbersome as your app grows.
  2. Provider: A minimalistic and straightforward package for state management, suitable for small to medium-sized projects.
  3. Bloc: A more advanced approach using streams and reactive programming for complex state management scenarios.
  4. GetX: It is a sophisticated microframework that allows us to create routing, manage states, and execute dependency injection.

Get — Into the Provider:

  • In Flutter, “Provider” refers to a design pattern and a package that helps manage the state of your application. It’s commonly used to efficiently share and update data between different parts of your app, such as widgets, without the need for prop drilling (passing data through multiple widget layers).
  • The “Provider” package in Flutter provides a way to manage and consume data using a provider class, which acts as a source of truth for your app’s state.

Currently, I’m using this provider version:

Press enter or click to view image in full size

Use the latest version 👉 Provider Package

Usage with an example:

In this journey, we’ll see how Flutter’s default counter application state will be managed using Flutter Provider.

  1. Create a Flutter provider with a counter application.
  2. The application must display a number 0 by initial value, an increment button, and a decrement button.
  3. Functionality: The number should be increment when you hit the increment button and it should be decrement when you hit the decrement button.
  4. Add the Flutter Provider package to your project using this command:
flutter pub add provider

5. Then run flutter pub get to get the dependencies.

Get Ruban Raghavendar K’s stories in your inbox

Join Medium for free to get updates from this writer.

6. Create a provider class for the counter application which should extend the changeNotifier.

// counter_provider.dart

import 'package:flutter/material.dart';
class CounterProvider extends ChangeNotifier {
// Methods
}

7. Create a counterValue variable and initiate it as 0 in the constructor.

// counter_provider.dart

import 'package:flutter/material.dart';

class CounterProvider extends ChangeNotifier {
int counterValue;

CounterProvider({
this.counterValue = 0,
});
}

8. Create an increment and decrement function to do the increment and decrement operations.

// counter_provider.dart

import 'package:flutter/material.dart';

class CounterProvider extends ChangeNotifier {
int counterValue;

CounterProvider({
this.counterValue = 0,
});

void incrementNumber() {
counterValue++;
notifyListeners();// To notify all the listeners that the value may change
}

void decrementNumber() {
counterValue--;
notifyListeners();
}
}

Please note :
Only you can able to access the notifyListeners() method by extending your class from ChangeNotifier. So make sure that you’ve extended your class from ChangeNotifier.

9. Add that provider to the main tree by using MultiProvider to access anywhere in the project.

// main.dart

import 'package:flutter/material.dart';
import 'package:practice_provider/home.dart';
import 'package:practice_provider/user_provider.dart';
import 'package:provider/provider.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
const MyApp({super.key});

@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(
create: (context) => CounterProvider(),
),
],
child: const MaterialApp(
debugShowCheckedModeBanner: false,
home: Home(),
),
);
}
}

MultiProvideruses the provider's property to take a list of providers and inject them into the widget-tree at the same level.

10. Append the values in the UI part.

// home.dart

Text(
// Use the toString() method to convert an integer to a string.
context.watch<CounterProvider>().counterValue.toString(),
),

In the above code, thewatch() method is used to listen to the changes.

// home.dart


// Increment
ElevatedButton(
onPressed: () {
context.read<CounterProvider>().incrementNumber();
},
child: const Text(
'+',
),
),

// Decrement
ElevatedButton(
onPressed: () {
context.read<CounterProvider>().decrementNumber();
},
child: const Text(
'-',
),
),
  • In the above code, theread() method is used not to listen but to access and change the state.
  • By calling the decrement function, the counter value will be decreased by 1, and the increment will be increased by 1.

Now that we've completed the counter application using the Provider, we can see the output:

Press enter or click to view image in full size
Press enter or click to view image in full size
Press enter or click to view image in full size
Initial | Increment | Decrement

I’ll push this code in GitHub, please make use of it.

Benefits for users:

  1. Simplicity: Provider offers a straightforward and easy-to-understand approach to state management in Flutter.
  2. Scoped Instances: It allows the creation of scoped instances, ensuring that the state is available only where needed in the widget tree.
  3. Reactive Programming: The provider supports a reactive programming style, resulting in efficient widget updates when the state changes.
  4. Minimal Boilerplate: Reduces the amount of boilerplate code, promoting clean and maintainable code.
  5. Community Support: Widely adopted in the Flutter community, the Provider comes with ample resources, tutorials, and community support.

Finale:

  • Flutter Provider state management offers a powerful yet simple solution for handling the state in Flutter applications.
  • With its scoped instances, reactive programming model, and seamless dependency injection, Provider provides an efficient and organized way to manage the state at various levels of the widget tree.
  • Overall, Flutter Provider emerges as a versatile and well-supported choice for state management, balancing ease of use with flexibility and scalability in Flutter applications.

I hope this journey will be more useful for us💯

If any Suggestions or Corrections, you’re always welcome!!!

Thank you for being a part of this journey🫂

See you on the next journey👋👋👋

Until then, Signing off:

Ruban❤️

--