flutter_state_management 0.8.1 copy "flutter_state_management: ^0.8.1" to clipboard
flutter_state_management: ^0.8.1 copied to clipboard

A collection of helper classes to make the use of ChangeNotifier easier for 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, String> {
  Counter() : super(const Active(data: 0));

  void increment() async {
    setWaiting(data: data);

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

    if (data > 20) {
     setFailed('greater than 20', data: data);
    } else {
      setActive(data: data + 1);
    }
  }
}

Or if you want the state to persist across restarts

class Counter extends PersistedStateNotifier<int, String> {
  Counter() : super(IsarKeyValue(), startState: 0);

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

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

    if (data > 20) {
      persistedState = Failed('greater than 20', data: data);
    } else {
      persistedState = Active(data: data + 1);
    }
  }
}

Handle State Changes in UI #

To only rebuild specific parts:

  1. 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'),
  ),
);

You can also use builderArg helper:

builder: counter.builderArg(
  onActive: ,
  onWaiting: ,
  onNone: ,
  onFailure: ,
),
  1. Or use StateNotifierBuilder that comes with this package and is more user friendly:
final counter = Counter();

counter.builder(
  onActive: (context, data) => Text(data.toString()),
),


\

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());
  }
}
3
likes
160
points
711
downloads

Publisher

verified publishermuha.dev

Weekly Downloads

A collection of helper classes to make the use of ChangeNotifier easier for state management

Repository (GitHub)
View/report issues

Documentation

API reference

License

MIT (license)

Dependencies

flutter

More

Packages that depend on flutter_state_management