flutter_onlooker 3.0.1 flutter_onlooker: ^3.0.1 copied to clipboard
A state management library that provides a simple solution for updating state and navigation.
Onlooker #
A state management library that provides a simple solution for updating state and navigation.
Usage #
Lets take a look at how to use flutter_onlooker
. The library provides: StateNotifier
, StateObserver
and StateNotifierProvider
classes.
StateNotifier
is responsible for registering and notifying states. Also it can emit navigation events. The main methods of this class:
observable<S>
registers observable state ofS
type.initial<S>
returns initial value for state ofS
type.latest<S>
returns the latest value for state ofS
type.contains<S>
checks whether a state ofS
type was registered before.notify<S>
notifies a new state ofS
type.navigate<T extends Object?>
notifies a new navigation event.
class IncrementStateNotifier extends StateNotifier {
int _counter = 0;
IncrementStateNotifier() {
observable<int>(initial: _counter);
}
void useCase() {
final initialState = initial<int>();
final latestState = latest<int>();
final containsState = contains<int>();
notify<int>(++_counter);
navigate<void>('/route-name', arguments: _counter);
}
}
StateObserver
handles building a widget in response to newstates
. It takes 3 parameters:
- required
builder
function that takes theBuildContext
andstate
, this function is responsible for returning a widget which is to be rendered. - An optional
notifier
that can be passed directly or with usingStateNotifierProvider
. - An optional
buildWhen
can be implemented for more granular control over how oftenStateObserver
rebuilds.
StateObserver<IncrementStateNotifier, int>(
builder: (_, state) {
return Text(
'$state',
style: Theme.of(context).textTheme.headlineMedium,
);
},
)
StateNotifierProvider
takes acreate
function that is responsible for creating theStateNotifier
,child
widget that will have access to theStateNotifier
instance viaProvider.of<StateNotifier>(context)
orcontext.read<StateNotifier>()
and optionalrouter
function that will receive navigation events.
StateNotifierProvider<IncrementStateNotifier>(
create: (_) => IncrementStateNotifier(),
child: const MyHomePage(title: 'Onlooker Demo'),
router: (context, routeName, arguments) {
return showDialog<void>(
context: context,
builder: (_) => AlertDialog(
title: Text("Route is '$routeName'"),
content: Text("You've clicked $arguments times!"),
),
);
},
)