LoginSignup
0
0

More than 1 year has passed since last update.

Flutter/Riverpod StateNotifierProviderでListを管理するときのUtils備忘録

Last updated at Posted at 2023-01-13

はじめに

 StateNotifierProvider便利ですよね〜。やっぱり大体の解説記事でコレ使ってますからね。
まず使って驚いたのですが、stateを更新するときは新しいListを作成しないといけないんですよね。(Riverpod完全理解民からしたら当たり前)
stateにinsert()したら画面が更新されなくてアレ??なんてことも見かけます。そんなときにいちいち値の追加や削除を書くのは時間がかかります(プログラマーたるもの怠惰であれ)。そこで、この記事ではstate用のinsert(),add(),remove()を作りたいと思います。もちろん画面も更新されますよ。

ベースとなるコード

@immutable
class Todo {
  const Todo({required this.id, required this.description, required this.completed});

  final String id;
  final String description;
  final bool completed;

  Todo copyWith({String? id, String? description, bool? completed}) {
    return Todo(
      id: id ?? this.id,
      description: description ?? this.description,
      completed: completed ?? this.completed,
    );
  }
}

class TodosNotifier extends StateNotifier<List<Todo>> {
  TodosNotifier(): super([]);

  void addTodo(Todo todo) {
    state = [...state, todo];
  }

  void removeTodo(String todoId) {
    state = [
      for (final todo in state)
        if (todo.id != todoId) todo,
    ];
  }

  void toggle(String todoId) {
    state = [
      for (final todo in state)
        if (todo.id == todoId)
          todo.copyWith(completed: !todo.completed)
        else
          todo,
    ];
  }
}

final todosProvider = StateNotifierProvider<TodosNotifier, List<Todo>>((ref) {
  return TodosNotifier();
});

このコードの中でもadd()でremove()は実装されていますね。
ですが、備忘録なので一応実装方法を書いておきます。

insert()

void _insert(Todo todo, int index) {
    state = [
        ...state.sublist(0, index),
        todo,
        ...state.sublist(index),
    ];
}

add()

void _add(Todo todo) {
    state = [...state, todo];
}

remove()

void _remove(int index) {
    state = [
        ...state.sublist(0, index),
        ...state.sublist(index + 1),
    ];
}

以上です。

 この記事に書いてあるコード自体は細心の注意を払って書いておりますが、動作の確認はしておりませんので、エラーが出たら直して使ってください。それでは!!

追記

https://docs-v2.riverpod.dev/docs/providers/notifier_provider
なんか、公式のサイトに知らんやつがいた。
その名も、「NotifierProvider」!!
誰か使ってないかな?

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