Flutter
Challenge 1
Build API state management with StateNotifier and AsyncValue.
Challenge 1 - StateNotifier and AsyncValue
In this challenge you will create a StateNotifier<AsyncValue<List<String>>>. You wrap the API call with AsyncValue.guard, which handles loading and error states automatically.
class PostNotifier extends StateNotifier<AsyncValue<List<String>>> {
PostNotifier() : super(const AsyncValue.loading()) {
_load();
}
Future<void> _load() async {
state = await AsyncValue.guard(() async => ['a', 'b']);
}
}
Exercise Define PostNotifier
Define PostNotifier extending StateNotifier<AsyncValue<List<String>>>. The constructor starts with AsyncValue.loading() and calls _load(). The async _load method assigns the result of AsyncValue.guard(() async => ['post1', 'post2']) to state. In main, create a PostNotifier instance, wait 100ms, and print state.value.
Show example solution
import 'package:flutter_riverpod/flutter_riverpod.dart';
class PostNotifier extends StateNotifier<AsyncValue<List<String>>> {
PostNotifier() : super(const AsyncValue.loading()) {
_load();
}
Future<void> _load() async {
state = await AsyncValue.guard(() async => ['post1', 'post2']);
}
}
void main() async {
final notifier = PostNotifier();
await Future.delayed(const Duration(milliseconds: 100));
print(notifier.state.value);
notifier.dispose();
}
Exercise Handle states with AsyncValue.when
In main, assign AsyncValue.data(['a', 'b']) to a variable state. Handle loading, data and error states with state.when: loading () => 'yukleniyor', data (v) => v.join(','), error (e, _) => 'hata: $e'. Print the result.
Show example solution
import 'package:flutter_riverpod/flutter_riverpod.dart';
void main() {
final state = AsyncValue.data(['a', 'b']);
final result = state.when(
loading: () => 'yukleniyor',
data: (v) => v.join(','),
error: (e, _) => 'hata: $e',
);
print(result);
}
Test yourself
-
When should the state property of StateNotifier be updated?
- When async operations complete and value is ready
- Never
- Every frame
- Only inside the constructor
Show answer
When async operations complete and value is ready — State gets its initial value in the constructor; it is updated with the guard result once async operations complete and the value is ready.
-
AsyncValue.guard call
state = await AsyncValue.____(() async => ['a', 'b']);
Show answer
state = await AsyncValue.guard(() async => ['a', 'b']);
-
StateNotifier and AsyncValue matches
- StateNotifier
- State manager
- AsyncValue
- Async state wrapper
- guard
- Catches errors
- StateNotifierProvider
- Provider
Next lesson: Challenge 2