Riverpodのfamilyを使う (Flutter)

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

family を使ってみる

検証コード

lib/main.dart

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

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

final familyProvider = Provider.family<String, String>((ref, id) {
  return "string: $id";
});

class MyApp extends ConsumerWidget {
  // This widget is the root of your application.
  
  Widget build(BuildContext context, WidgetRef ref) {
    final provider1 = ref.watch(familyProvider("111"));
    final provider2 = ref.watch(familyProvider("222"));

    print("provider1: ${provider1}");
    print("provider2: ${provider2}");

    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            title: const Text('My First app'),
          ),
          body: null),
    );
  }
}

デバッグコンソール

I/flutter ( 9129): provider1: string: 111
I/flutter ( 9129): provider2: string: 222

参考


SHARE

Profile picture

Written by tamesuu