flutter_state_management

Creator: coderz1093

Last updated:

0 purchases

TODO
Add to Cart

Description:

flutter state management

Flutter State Management #
Just a couple of utility classes to make it easier to use Flutter framework's built-in
ChangeNotifier
and Listenable for state management.
Features #

No learning curve if you already know Flutter
Simple package based on ChangeNotifier (No bloatware)

Usage #
Create your model class
class Counter extends StateNotifier<int, Error> {
Counter() : super(const Loaded(data: 0));

void increment() async {
state = Loading(data: data);

await Future.delayed(const Duration(seconds: 2));

if (data > 20) {
state = Failed(error: StateError('greater than 20'), data: data);
} else {
state = Loaded(data: data + 1);
}
}
}
copied to clipboard
Or if you want the state to persist across restarts
class Counter extends PersistedStateNotifier<int, int> {
Counter() : super(IsarKeyValue(), startState: 0);

void increment() async {
persistedState = Loading(data: data);

await Future.delayed(const Duration(seconds: 2));

if (data > 20) {
persistedState = Failed(error: StateError('greater than 20'), data: data);
} else {
persistedState = Loaded(data: data + 1);
}
}
}
copied to clipboard
Handle State Changes in UI #
To only rebuild specific parts:

Use ValueListenableBuilder from the Flutter framework:

final counter = Counter();

ValueListenableBuilder(
valueListenable: counter,
child: Text()
builder: (context, state, child) => // return updated UI here (can also use counter.builderArg here)
child: const Text('Hello'),
),
);
copied to clipboard
You can also use builderArg helper:
builder: counter.builderArg(
onLoaded: ,
onLoading: ,
onIdle: ,
onFailure: ,
),
copied to clipboard

Or use StateNotifierBuilder that comes with this package and is more user friendly:

final counter = Counter();

counter.builder(
onLoaded: (context, data) => Text(data.toString()),
),
copied to clipboard

\
To rebuild whole widget
Convert your existing StatelessWidget to RStatelessWidget, and StatefulWidget to RStatefulWidget
and and just watch the model inside the build method:
class CounterText extends RStatelessWidget {
@override
Widget build(BuildContext context) {
counter.watch(context); // call watch inside the build method (do not use any if)
return Text(data.toString());
}
}
copied to clipboard

License

For personal and professional use. You cannot resell or redistribute these repositories in their original state.

Files:

Customer Reviews

There are no reviews.