Step13 ChangeNotifierProvider
Goal of this step
- Learn how to use ChangeNotifierProvider
- Notify Changes of
isAuthenticated
To Provider
In this step, let's solve last step problem.
We want to change the Provider's isAuthenticated
value.
Ref:
- https://flutter.dev/docs/development/data-and-backend/state-mgmt/simple#changenotifier
- https://alligator.io/flutter/state-management/#change-notifier
Make GlobalState class
To use ChangeNotifierProvider
, we need to make new Class which extends ChangeNotifier
.
I just named it GlobalState
class. It has bool isAuthenticated
Make new file lib/global_state.dart
Replace existing provider code
Replace (home_page.dart
and home_drawer.dart
)
with
So the code looks
Add function to notify Provider's change
In lib/pages/login_page.dart
and lib/pages/register_page.dart
In lib/widgets/home_drawer.dart
These codes are just doing same thing in document: https://flutter.dev/docs/development/data-and-backend/state-mgmt/simple#providerof
[About listen of Provider.of
]https://pub.dev/documentation/provider/latest/provider/Provider/of.html
Test it
Test to check it works well...
Review this approach
To call
is troublesome...
BUT! There is a nicer way!
"StreamProvider".
Let's try this in the next step.