Pragmatic State Handling in Flutter | by Erlend | Feb, 2022

Which state management solution works best for you?

Erlend
Photo by NordWood Themes on Unsplash

Basic state

class UserState extends ValueNotifier<User?> {
UserState(User? user) : super(user);
}
final userState = UserState(null);

More complex state


class UserState extends ValueNotifier<User?> {
UserState(User? user) : super(user) {
FirebaseAuth.instance.userChanges().listen((User? user) {
value = user;
});
}
}

Listen for state changes

@override
Widget build(BuildContext context) {
return ValueListenableBuilder<User?>(
valueListenable: userState,
builder: (context, User? user, child) {
// TODO..
}
);
}
userState.addListener(() { 
User user? userState.value;
// TODO..
});

Listen for multiple state changes

return AnimatedBuilder(
animation: Listenable.merge([
userState,
someOtherState,
]),
builder: (context, child) {
final User? user = userState.value;
final OtherState? otherValue = someOtherState.value;

Preload state

class SomeState extend ValueNotifier {
Future<void> init() async {
// TODO do async work and return
}
}
home: FutureBuilder(
future: Future.wait([
userState.init(),
otherState.init(),
]),
builder: (context, snapshot) {
// TODO ..
},
)

State metadata

class StateEvent<T> {
final T? data;
final bool loading;
final Object? error;
}
Want to Connect?Please get in touch on Twitter @apptakk if you have any questions or comments

Leave a Comment