LoginSignup
0
0

More than 1 year has passed since last update.

AysncValueメモ

Posted at

AsyncValueとは

Riverpod パッケージに含まれる非同期データを安全に扱うためのユティリティクラス。
非同期のloadingやerror処理を扱える。whenを使ってloading時にプログレスインディケーターを表示したりエラー処理、データを表示する事ができる。

AyncValueにObjectを入れてやると非同期処理時にそのObjectの状況を簡単に監視できるそう。

AsyncValue
/// A provider that asynchronously exposes the current user
final userProvider = StreamProvider<User>((_) async* {
  // fetch the user
});

class Example extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final AsyncValue<User> user = ref.watch(userProvider);

    return user.when(
      loading: () => CircularProgressIndicator(),
      error: (error, stack) => Text('Oops, something unexpected happened'),
      data: (user) => Text('Hello ${user.name}'),
    );
  }
}

LoadingやError Stateを使わない場合は直接AsyncValueの中身(Value)にアクセスする事ができる。

valueはNullable。

AsyncValue Value
Widget build(BuildContext context, WidgetRef ref) {
  // reads the data state directly – will be throw during loading/error states
  final User user = ref.watch(userProvider).value;

  return Text('Hello ${user.name}');
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0