flutter_onlooker 2.0.3
flutter_onlooker: ^2.0.3 copied to clipboard
A state management library which provides a simple solution for updating state and navigation.
Onlooker #
A state management library which 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.
StateNotifieris responsible for registering and notifying states. Also it can emit navigation events. The main methods of this class:
observable<S>- registers observable state ofStype.initial<S>- returns initial value for state ofStype.latest<S>- returns the latest value for state ofStype.contains<S>- checks whether a state ofStype was registered before.notify<S>- notifies a new state ofStype.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>(_counter);
}
}
StateObserverhandles building a widget in response to newstates. It takes 3 parameters:
- required
builderfunction which takes theBuildContextandstate, this function is responsible for returning a widget which is to be rendered. - An optional
notifierwhich can be passed directly or with usingStateNotifierProvider. - An optional
buildWhencan be implemented for more granular control over how oftenStateObserverrebuilds.
StateObserver<IncrementStateNotifier, int>(
builder: (_, state) {
return Text(
'$state',
style: Theme.of(context).textTheme.headline4,
);
},
)
StateNotifierProvider- takes acreatefunction that is responsible for creating theStateNotifier,childwidget which will have access to theStateNotifierinstance viaProvider.of<StateNotifier>(context)orcontext.read<StateNotifier>()and optionalrouterfunction which will receive navigation events.
StateNotifierProvider<IncrementStateNotifier>(
create: (_) => IncrementStateNotifier(),
child: const MyHomePage(title: 'Onlooker Demo'),
router: (context, dynamic route) {
return showDialog<void>(
context: context,
builder: (_) => AlertDialog(
title: const Text('Counter info'),
content: Text('You\'ve clicked $route times!'),
),
);
},
)