The Consumer Widget: Application

Continue to learn about the consumer widget and how you can implement it in an actual application.

How to notify listeners?

We need the ChangeNotifierProvider widget that provides an instance of a ChangeNotifier to its descendants. It comes from the provider package.

Now our task becomes much more manageable. Because we place ChangeNotifierProvider at the top of all widgets, any descendant widget can access the state from it directly.

Press + to interact
import 'package:flutter/material.dart';
import 'package:flutter_provider_explained_for_beginners/model/counting_the_number.dart';
import 'package:flutter_provider_explained_for_beginners/view/my_home_page.dart';
import 'package:provider/provider.dart';
void main() {
runApp(
// ChangeNotifierProvider, unlike ChangeNotifier, comes from the Provider package
// and it provides an instance of a ChangeNotifier to the widgets,
// which have already subscribed to it
// we should place the ChangeNotifierProvider Just above the widgets that need to access it.
// you will understand provider better if you already have understood how
// InheritedWidget works
ChangeNotifierProvider(
create: (context) =>
CountingTheNumber(), // designed Model is provided to the desired widgets
child: MyApp(),
),
);
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}

We can now provide the CountingTheNumber model to any descendant widgets in our app through the ChangeNotifierProvider. We have already declared ChangeNotifierProvider at the top so we can start using it.

How can we access the changed data? How can we change the state through the consumer widget?

We’re closing towards the lesser-known facts of Provider package. As we have just seen, the ...

Get hands-on with 1400+ tech skills courses.