1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

AsyncNotifierの使い方を学んでます

Posted at

前提

  • Flutter勉強中です
  • 間違っている可能性もあります

バージョン

flutter_riverpod: ^2.4.10
freezed_annotation: ^2.4.1
json_annotation: ^4.8.1
riverpod_generator: ^2.4.0
riverpod_annotation: ^2.3.5

使ってみた

こちらはコメントを扱うViewModelです。

@riverpod
class ProblemCommentViewModel extends _$ProblemCommentViewModel {
  final commentController = TextEditingController();
  final scrollController = ScrollController();

  SecureStorageRepository get secureStorage =>
      ref.read(secureStorageRepositoryProvider);
  ProblemRepository get problemRepository =>
      ref.read(problemRepositoryProvider);
  UserRepository get userRepository => ref.read(userRepositoryProvider);

  @override
  FutureOr<List<ProblemCommentStateOfDay>?> build({
    required String problemId,
  }) async {
    // 最初に保持する値の処理
    return commentStateOfDay;
  }

  Future<void> postComment({required Problem problem}) async {
    // 処理

    // stateを取得
    final prevState = state.asData?.value;

    // stateの更新
    state = await AsyncValue.guard(() async {
      if (prevState == null) {
        return [newStateOfDay];
      }

      // リストの管理にも詰まったのでおいておきます…
      final List<ProblemCommentStateOfDay> newState = List.from(prevState);

      final lastItem = newState.last.copyWith(
        comments: [
          newComment,
          ...newState.last.comments,
        ],
      );
      return newState;
    });
  }
}

もっといい書き方あったら教えてください!

自分なりの理解

  • ViewModel内のメソッドで使える
HogeRepository get hogeRepo =>
      ref.read(hogeRepositoryProvider);
  • build()
build(引数)

でref.watchの時引数を渡せる

続くかもです。(24/03/29)

1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?