RiverpodのStateNotifierProviderを使う (Flutter)

November 02, 2022

確認環境

$ flutter --version
Flutter 3.3.4 • channel stable • https://github.com/flutter/flutter.git
Framework • revision eb6d86ee27 (3 weeks ago) • 2022-10-04 22:31:45 -0700
Engine • revision c08d7d5efc
Tools • Dart 2.18.2 • DevTools 2.15.0

pubspec.yaml

dependencies:
  ...
  flutter_hooks: ^0.18.5+1
  hooks_riverpod: ^2.0.2
  ...

StateNotifierProviderを使ってみる

使いどころ

ステートを変更するロジックも一緒に管理する時に使います。

検証コード

+ ボタンを押すと一覧にタスクが増えていきます。

import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';

void main() {
  runApp(ProviderScope(child: MyApp()));
}

class Todo {
  const Todo(this.id, this.name);
  final String id;
  final String name;
}

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

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

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

class MyApp extends ConsumerWidget {
  // This widget is the root of your application.
  
  Widget build(BuildContext context, WidgetRef ref) {
    List<Todo> todos = ref.watch(todosProvider);
    final notifier = ref.watch(todosProvider.notifier);

    void addTodo() {
      final newTodo = Todo('固定id', 'hoge');
      notifier.addTodo(newTodo);
    }

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('My First app'),
        ),
        body: ListView(
          children: [
            for (final todo in todos)
              CheckboxListTile(
                  value: false, onChanged: null, title: Text(todo.name)),
          ],
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: addTodo,
          child: const Icon(Icons.add),
        ),
      ),
    );
  }
}

参考


SHARE

Profile picture

Written by tamesuu