Riverpodのref.listenを使ってみる (Flutter)

November 20, 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
  ...

ref.listen を使ってみる

検証コード

lib/main.dart

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

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

class Counter {
  const Counter(this.num);
  final int num;
}

class CounterNotifier extends StateNotifier<Counter> {
  CounterNotifier() : super(const Counter(0));

  void increment() {
    state = Counter(state.num + 1);
  }
}

final CounterProvider = StateNotifierProvider<CounterNotifier, Counter>((ref) {
  return CounterNotifier();
});

class MyApp extends ConsumerWidget {
  // This widget is the root of your application.
  
  Widget build(BuildContext context, WidgetRef ref) {
    ref.listen<Counter>(CounterProvider, (previous, next) {
      print("previous: ${previous?.num} / next: ${next.num}");
      print("ここで、Provider更新後に実行したい処理");
    });

    void increment() {
      ref.read(CounterProvider.notifier).increment();
    }

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('My First app'),
        ),
        body: Text("Counter.num: ${ref.watch(CounterProvider).num}"),
        floatingActionButton: FloatingActionButton(
          onPressed: increment,
          child: const Icon(Icons.add),
        ),
      ),
    );
  }
}

+ ボタンを押下 (1回目)

デバッグコンソール

I/flutter ( 8245): previous: 0 / next: 1
I/flutter ( 8245): ここで、Provider更新後に実行したい処理

+ ボタンを押下 (2回目)

デバッグコンソール

I/flutter ( 8245): previous: 1 / next: 2
I/flutter ( 8245): ここで、Provider更新後に実行したい処理

参考


SHARE

Profile picture

Written by tamesuu