Codementor Events

Flutter state management using Provider

Published May 12, 2019

After experimenting with multiple ways to manage state in flutter, Provider looks solid and easy to use.

Here are the various ways of maintaining state in flutter:

Scoped Model
BLoc
Redux
MobX

Flutter provider with example:

A dependency injection system built with widgets for widgets. provider is mostly syntax sugar for InheritedWidget, to make common use-cases straightforward.

Let's walk through most popular 'Counter Widget':

Add this to your package's pubspec.yaml file:
dependencies:
provider: ^2.0.0+1

1. Create your model class.

import 'package:flutter/cupertino.dart';

class CounterModel with ChangeNotifier {
  int _counter = 0;

  getCounter() => _counter;

  setCounter(int counter) => _counter = counter;

  void incrementCounter() {
    _counter++;
    notifyListeners();
  }

  void decrementCounter() {
    _counter--;
    notifyListeners();
  }
}

2. Create your Widget.
Here you widget is 'StatelessWidget'.

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

import 'counter_model.dart';

class CounterView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final counterModel = Provider.of<CounterModel>(context);

    return Scaffold(
      appBar: AppBar(
        title: Text('Provider Demo'),
      ),
      body: Center(
        child: Text(
          'Counter Value is: ${counterModel.getCounter()}',
          style: TextStyle(fontSize: 24.0),
        ),
      ),
      floatingActionButton: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          FloatingActionButton(
            onPressed: () => counterModel.incrementCounter(),
            tooltip: 'Increment',
            child: Icon(Icons.add),
          ),
          SizedBox(width: 30),
          FloatingActionButton(
            onPressed: () => counterModel.decrementCounter(),
            tooltip: 'Decrement',
            child: Icon(Icons.remove),
          ),
        ],
      ),
    );
  }
}

3.Your Main.dart.

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:provider_demo/counter_model.dart';
import 'package:provider_demo/counter_view.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.indigo,
      ),
      home: ChangeNotifierProvider<CounterModel>(
        builder: (_) => CounterModel(),
        child: CounterView(),
      ),
    );
  }
}

Simulator.png

That's it, enjoy šŸ˜ƒ

Discover and read more posts from Sunil Mishra
get started
post comments5Replies
maha14mr
5 years ago

good one!

sagar bagsariya
5 years ago

How can we change data of HomePage from another page ? like navigate next page from home and change counter value from that page ?

Good Grief
5 years ago
Paulo Gorenstein
6 years ago

Simpleā€¦the bestā€¦could you give an example of multiple Classes Inherited by Multiples Widgets?

Sunil Mishra
6 years ago

if you have complex multiple models and widget tree, then Multiprovider can be most suitable way to deal with.
https://pub.dev/packages/provider#multiprovider

Show more replies