You can nudge your life in a new direction every day.

Flutter: Another Simple Provider Example

Submitted by admin on Fri, 09/25/2020 - 14:27

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.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() {
    create: (_) => Foo(),
    child: MyApp(),

class MyApp extends StatelessWidget {
  Widget build(BuildContext context) {
    var value =<Foo>().value;
    //This will also work,
    // var value = Provider.of<Foo>(context).value;
    return MaterialApp(
      home: Scaffold(
          body: Center(
              child: Column(
                  children: [
            //Call property of Foo
            Text("Using Provider: " + value.toString()),
            //Use Consumer to build Widget displaying value
                builder: (_, foo, child) =>
                    Text("Using Consumer: " + foo.value.toString())),
              onPressed: () {
                Provider.of<Foo>(context, listen: false).change();
              child: Text('Change State', style: TextStyle(fontSize: 20)),
              onPressed: () {
                //Either this or this Provider.of<Foo>(context, listen: false).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;

  bool get value {
    return _value;

  void change() {
    _value = false;

  void reset() {
    _value = true;