在 StateNotifier 子類中使用 AsyncValue.guard 替代 try/catch
更新時間:2023-11-07 19:11
在編寫自己的StateNotifier
子類時,通常會使用try/catch塊來處理可能失敗的Futures:
class SignOutButtonController extends StateNotifier<AsyncValue> {
SignOutButtonController({required this.authRepository})
: super(const AsyncValue.data(null));
final AuthRepository authRepository;
Future<void> signOut() async {
try {
state = const AsyncValue.loading();
await authRepository.signOut(); // this future can fail
state = const AsyncValue.data(null);
} catch (e) {
state = AsyncValue.error(e);
}
}
}
在這種情況下,AsyncValue.guard
是一個方便的替代方法,它為我們處理了所有繁重的工作:
Future<void> signOut() async {
state = const AsyncValue.loading();
state = await AsyncValue.guard(() => authRepository.signOut());
}
以下是在 AsyncValue
類中實現此方法的方式:
abstract class AsyncValue<T> {
static Future<AsyncValue<T>> guard<T>(Future<T> Function() future) async {
try {
return AsyncValue.data(await future());
} catch (err, stack) {
return AsyncValue.error(err, stackTrace: stack);
}
}
}