跳到主要内容

在 StateNotifier 子类中使用 AsyncValue.guard 替代 try/catch

管

管理员

flutter

2023年11月07日 1,990 次阅读
本页目录

在编写自己的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);
    }
  }
}
 

相关

相关文章

同分类文章 →
2026年10月31日 flutter

`auth()->id()` 到底返回谁?Sanctum 多态令牌与双会员系统的踩坑记录

## 引子先看一段看起来很正常的代码:```php$userId = auth('sanctum')-&gt;id();if ($userId) {    $res['isLiked'] = $this-&gt;likes()        -&gt;where('user_id', $userId

2026年07月28日 flutter

Dart 3 记录(Records)和密封类(Sealed classes)

Dart 3 引入了几个极其强大的语言特性,其中最耀眼、对我们日常开发改变最大的就是 记录(Records) 和 密封类(Sealed classes),它们配合 模式匹配(Pattern Matching),让 Dart 的表现力达到了现代编程语言(如 Swift、Kotlin、Rust

2026年06月29日 flutter

flutter的 Clean Architecture架构设计

Clean Architecture(清晰架构)是一种将应用程序分层的设计模式,强调关注点分离与依赖规则,通过将业务逻辑与框架、UI、数据源解耦,提升代码的可测试性、可维护性与可扩展性。在 Flutter/Dart 环境下,Clean Architecture 通

微信

扫码加我微信

微信二维码