09 Flutter - State
State
UI - f(state)
- Flutter UI is function of state - UI = f(state)
- Declarative style vs imperative
- Declarative - Flutter builds its user interface to reflect the current state of your app
- There is no TextField.setText()
For example, in Flutter it’s okay to rebuild parts of your UI from scratch instead of modifying it. Flutter is fast enough to do that, even on every frame if needed.
Types of state
- State - data needed to rebuild UI at any moment in time
- Ephemeral state - state contained in a single widget setState()
- App state – state shared across many parts of app (sometimes also called shared state)
- Package "provider"
Keep the state above the widgets that use it (lifting state up)
Addin package
https://pub.dev/packages/provider
pubspec.yaml
1 2 3 4 |
|
Using callbacks
- NB! Widgets are immutable – they get destroyed and replaced by new ones.
- Dart’s functions are first class objects, so you can pass callbacks around.
1 2 3 4 5 6 7 8 9 10 11 |
|
Provider 1
-
Passing around callbacks – there is lot of them - finally. No good.
-
Flutter has special low-level widgets for state handling
- InheritedWidget
- InheritedNotifier
- InheritedModel
-
Easy to use wrapper around these is
- Provider
Provider 2
-
ChangeNotifier provides change notification to its listeners. You can subscribe to its changes. (It is a form of Observable).
-
ChangeNotifierProvider is the widget that provides an instance of a ChangeNotifier to its descendants.
-
Consumer – get access to state, widget is recreated when state changes
-
Provider.of – get access to state, widget is NOT recreated when state changes
Model - POCO
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
ChangeNotifier
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|
State lifting
ChangeNotifierProvider
State in HomeScreen
1 2 3 4 5 6 7 8 9 10 |
|
Consumer
Widget is recreated on every state change!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
Provider.Of
Widget is not recreated on state change (possibly)!
1 2 3 4 5 6 7 8 9 10 11 |
|
Recap
State inside widget – StatefulWidget and setState((){…})
App State – use Provider package
- ChangeNotifier – define ModelClass (extend or mixin ChangeNotifier)
- ChangeNotifierProvider
- state holder in upper component - Consumer
- widget accesses state, gets recreated on state change - Provider.of
(context, listen: false) – access state in widgets, which are not UI dependent of state (action buttons for example)
Multiple states, proxy
MultiProvider
1 2 3 4 5 6 7 |
|
ProxyProvider – generic provider that builds a value based on other providers
1 2 3 4 5 |
|