跳到主要内容

在 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);
    }
  }
}
 

Related

相关文章

同分类文章 →
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 通

2025年12月22日 flutter

Riverpod 实战:如何优雅地实现网络请求的防抖与取消

在开发复杂的应用程序时,管理网络请求的生命周期至关重要。例如,用户在搜索框快速输入时可能会触发大量请求,或者在请求完成前离开页面,导致不必要的资源浪费。本文将介绍如何在 Riverpod 中利用 ref.onDispose 和&ldquo;

WeChat

扫码加我微信

微信二维码