Simplifying state management in flutter with provider

A graphic illustrating state management concepts in Flutter, showing various state management options.

State management is a crucial aspect of building robust and maintainable Flutter applications. Various state management solutions are available, including setState for simple state updates, InheritedWidget and InheritedModel for sharing data down the widget tree, and more advanced options like Bloc and Redux, which offer predictable state containers and separation of business logic. However, these solutions can introduce complexity and boilerplate code. Among these, the Provider package stands out for its simplicity, efficiency, and minimal boilerplate, making it an excellent choice for both small and large applications. In this blog post, we’ll explore how to use Provider to manage state in Flutter apps effectively.

What is provider?

Provider is a wrapper around InheritedWidget, making it easier to manage state and dependencies. It was created by Remi Rousselet and has become one of the most popular packages for state management in Flutter due to its simplicity and flexibility.

Why use provider?

  • Simplifies State Management: Provider abstracts away the complexity of managing state.
  • Ease of Use: Its straightforward API makes it beginner-friendly.
  • Scalability: Provider scales well with your application, making it suitable for both small and large projects.
  • Community and Support: As a widely-used package, it has extensive documentation and community support.


Getting started with provider

To get started with Provider, you need to add it to your project. Open your pubspec.yaml file and add the following dependency

Run flutter pub get to install the package.


Basic usage


Creating a changenotifier

Create a class that extends ChangeNotifier. This class will contain the state and logic of your application.


Providing the State

Wrap your widget tree with ChangeNotifierProvider to provide the state to your widgets.


Consuming the State

Use Consumer or Provider.of to access the state in your widgets.

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'counter.dart';

class CounterScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Provider Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Consumer<Counter>(
              builder: (context, counter, child) {
                return Text(
                  '${counter.count}',
                  style: Theme.of(context).textTheme.headline4,
                );
              },
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Provider.of<Counter>(context, listen: false).increment();
        },
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}


Best practices

  1. Avoid Business Logic in UI: Keep your business logic in your model classes.
  2. Use Selector: Use Selector to optimize performance by selecting only the parts of the state that your widget depends on.
  3. Modularize Your Code: Split your code into small, manageable pieces.


Conclusion

Provider is a powerful and flexible solution for state management in Flutter applications. Its simplicity and ease of use make it a great choice for both beginners and experienced developers. By following the best practices and utilizing advanced features, you can create scalable and maintainable applications. You can check the providers sample project here.

WRITTEN BY
Aathithyan Siriramachchanthiran

Our latest blogs

Dive into our blogs and gain insights

"Startups and product development"

State management is a crucial aspect of building robust and maintainable... 

"BrowserStack"

Losing a keystore file, which is essential for signing an Android application ...

"Demystifying serverless computing"

A regular expression is a sequence of characters that pattern in text....

Have you got an idea?

Transform your vision into reality with our custom software solutions, designed to meet your unique needs and aspirations.

"Have you got an idea?"