Flutter
Meydan okuma 1
StateNotifier ve AsyncValue ile API state yönetimi yaparsın.
Meydan okuma 1 - StateNotifier ve AsyncValue
Bu meydan okumada bir StateNotifier<AsyncValue<List<String>>> oluşturacaksın. AsyncValue.guard ile API çağrısını sarar, loading ve error durumlarını otomatik yönetirsin.
class PostNotifier extends StateNotifier<AsyncValue<List<String>>> {
PostNotifier() : super(const AsyncValue.loading()) {
_load();
}
Future<void> _load() async {
state = await AsyncValue.guard(() async => ['a', 'b']);
}
}
Uygulama PostNotifier tanımla
PostNotifier adında StateNotifier<AsyncValue<List<String>>> tanımla. Constructor AsyncValue.loading() ile başlasın ve _load() çağırsın. _load async metodu state'e AsyncValue.guard(() async => ['post1', 'post2']) sonucunu atasın. main'de PostNotifier örneği al, 100ms bekle, state.value'yu yazdır.
Örnek çözümü göster
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();
}
Uygulama AsyncValue.when ile durum işle
main içinde state değişkenine AsyncValue.data(['a', 'b']) ata. state.when ile loading, data ve error durumlarını işle: loading () => 'yukleniyor', data (v) => v.join(','), error (e, _) => 'hata: $e'. Sonucu yazdır.
Örnek çözümü göster
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);
}
Kendini test et
-
StateNotifier'ın state özelliği ne zaman güncellenmeli?
- Async işlemler bittiğinde ve değer hazır olduğunda
- Asla
- Her frame
- Yalnızca constructor içinde
Cevabı göster
Async işlemler bittiğinde ve değer hazır olduğunda — State, constructor'da başlangıç değerini alır; async işlemler bitip değer hazır olduğunda guard sonucuyla güncellenir.
-
AsyncValue.guard çağrısı
state = await AsyncValue.____(() async => ['a', 'b']);
Cevabı göster
state = await AsyncValue.guard(() async => ['a', 'b']);
-
StateNotifier ve AsyncValue eşleşmeleri
- StateNotifier
- State yöneticisi
- AsyncValue
- Async durum sarmalayıcı
- guard
- Hata yakalar
- StateNotifierProvider
- Provider
Sıradaki ders: Meydan okuma 2