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

November 23, 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.refresh を使ってみる

検証コード

  • + ボタンを押すと、1ずつカウントアップされていきます。
  • refresh ボタンを押すと、カウントが0になります。

lib/main.dart

import 'package:first_app/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);
  }

  void display() {
    print(state.num);
  }
}

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) {
    final counter = ref.watch(CounterProvider);

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

    void refresh() {
      print('refresh');
      ref.refresh(CounterProvider);
      ref.read(CounterProvider.notifier).display();
    }

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('My First app'),
        ),
        body: Column(
          children: [
            Text("Counter.num: counter: ${counter.num}"),
            ElevatedButton(onPressed: refresh, child: const Text('refresh'))
          ],
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: increment,
          child: const Icon(Icons.add),
        ),
      ),
    );
  }
}

+ ボタンを2回押下

I/flutter ( 8755): increment
I/flutter ( 8755): 1
I/flutter ( 8755): increment
I/flutter ( 8755): 2

refresh ボタンを押下

I/flutter ( 8755): refresh
I/flutter ( 8755): 0

参考


SHARE

Profile picture

Written by tamesuu