State Management with Flutter Provider

A portrait painting style image of a pirate holding an iPhone.

by The Captain

on
August 2, 2023

Flutter Provider Package: Simplifying State Management

State management is a crucial aspect of developing robust and performant Flutter applications. One popular solution for state management is the Flutter Provider package. It simplifies state management by leveraging the InheritedWidget and provider classes.

To get started with the Flutter Provider package, you need to add it as a dependency in your `pubspec.yaml` file:

dependencies:
  flutter:
    sdk: flutter
  provider: ^6.0.0

Next, wrap your root widget with a `MultiProvider` widget. The `MultiProvider` widget allows you to provide multiple instances of different types of providers to your widget tree. For example:

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => CounterProvider()),
        Provider(create: (_) => UserRepository()),
      ],
      child: MaterialApp(
        title: 'Flutter Provider Example',
        home: HomeScreen(),
      ),
    );
  }
}

In the example above, we have created two types of providers: `ChangeNotifierProvider` and `Provider`. The `ChangeNotifierProvider` is used for managing mutable state using the `ChangeNotifier` class. The `Provider` is used for providing immutable dependencies.

To create a provider class, simply extend `ChangeNotifier` or create a custom class and implement the `ChangeNotifier` mixin. Here's an example of a simple counter provider:

class CounterProvider with ChangeNotifier {
  int _count = 0;

  int get count => _count;

  void increment() {
    _count++;
    notifyListeners();
  }
}

In the example above, the `CounterProvider` extends `ChangeNotifier` and provides a `count` property and an `increment` method. Whenever the `count` is updated, the `notifyListeners` method is called to notify all the listeners about the change.

To access the state provided by the provider, you can use the `Provider.of` method:

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final counter = Provider.of(context);

    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Provider Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'Count: ${counter.count}',
              style: TextStyle(fontSize: 24),
            ),
            ElevatedButton(
              onPressed: () => counter.increment(),
              child: Text('Increment'),
            ),
          ],
        ),
      ),
    );
  }
}

In the example above, the `Provider.of` method is used to retrieve the `CounterProvider` instance. The `increment` method is called when the button is pressed, updating the count and triggering a rebuild of the widget tree.

With the Flutter Provider package, you can easily manage and access state throughout your widget tree. It simplifies the state management process by providing a convenient way to handle mutable and immutable state. By using providers, you can easily organize and decouple your code, making it more maintainable and scalable.