Use AsyncValue.guard rather than try/catch inside your AsyncNotifier subclasses

When writing your own AsyncNotifier subclasses, it’s quite common to use try/catch blocks to deal with Futures that can fail:

@riverpod
class SignOutButtonController extends _$SignOutButtonController {
  @override
  FutureOr<void> build() {
    // no-op
  }
 
  Future<void> signOut() async {
    try {
      state = const AsyncValue.loading();
      await ref.read(authRepositoryProvider).signOut();
      state = const AsyncValue.data(null);
    } catch (e) {
      state = AsyncValue.error(e);
    }
  }
}

In such cases, AsyncValue.guard is a convenient alternative that does all the heavy-lifting for us:

Future<void> signOut() async {
  final authRepository = ref.read(authRepositoryProvider);
  state = const AsyncValue.loading();
  state = await AsyncValue.guard(authRepository.signOut);
}

Here’s how this method is implemented in the the AsyncValue class:

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

Learn more here: AsyncValue.guard() method.

Happy coding!

Want More?

Invest in yourself with my high-quality Flutter courses.

Flutter in Production

Flutter in Production

Learn about flavors, environments, error monitoring, analytics, release management, CI/CD, and finally ship your Flutter apps to the stores. 🚀

Flutter Foundations Course

Flutter Foundations Course

Learn about State Management, App Architecture, Navigation, Testing, and much more by building a Flutter eCommerce app on iOS, Android, and web.

Flutter & Firebase Masterclass

Flutter & Firebase Masterclass

Learn about Firebase Auth, Cloud Firestore, Cloud Functions, Stripe payments, and much more by building a full-stack eCommerce app with Flutter & Firebase.

The Complete Dart Developer Guide

The Complete Dart Developer Guide

Learn Dart Programming in depth. Includes: basic to advanced topics, exercises, and projects. Last updated to Dart 2.15.

Flutter Animations Masterclass

Flutter Animations Masterclass

Master Flutter animations and build a completely custom habit tracking application.