Skip to main content

Flutter: Another Simple Provider Example

I'm working through simple examples of state management using the provider package in Flutter.

This example illustrates the use of and how they are interchangeable.

  • Provider.of<Foo>

  • Consumer<Foo>

  • context.read<T>

  • context.watc<T>

My file struture is as follows:

  • lib/main.dart
    • This is where I declare my provider and present the UI
  • lib/model/models.dart
    • This is where I keep class Foo, it's properties and methods.

In lib/main.dart

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

void main() {
  runApp(ChangeNotifierProvider(
    create: (_) => Foo(),
    child: MyApp(),
  ));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var value = context.watch<Foo>().value;
    //This will also work,
    // var value = Provider.of<Foo>(context).value;
    //print(value);
    return MaterialApp(
      home: Scaffold(
          body: Center(
              child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
            //Call property of Foo
            Text("Using Provider: " + value.toString()),
            //Use Consumer to build Widget displaying value
            Consumer<Foo>(
                builder: (_, foo, child) =>
                    Text("Using Consumer: " + foo.value.toString())),
            RaisedButton(
              onPressed: () {
                Provider.of<Foo>(context, listen: false).change();
              },
              child: Text('Change State', style: TextStyle(fontSize: 20)),
            ),
            RaisedButton(
              onPressed: () {
                //Either this or this Provider.of<Foo>(context, listen: false).reset();
                context.read<Foo>()..reset();
              },
              child: Text('Change Back', style: TextStyle(fontSize: 20)),
            )
          ]))),
    );
  }
}

In lib/models/model.dart

import 'package:flutter/material.dart';

class Foo extends ChangeNotifier {
//Initial private state of the value
  var _value = true;

//Getter
  bool get value {
    return _value;
  }

//Method
  void change() {
    _value = false;
    notifyListeners();
  }

  //Method
  void reset() {
    _value = true;
    notifyListeners();
  }
}