RiverpodのStreamProviderを使う (Flutter)

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

StreamProviderを使ってみる

StreamProvider は FutureProvider の Stream 版です。

検証コード

lib/assets/config.json

{
  "a": 1,
  "b": 3
}

lib/assets/config2.json

{
  "a": 1,
  "b": 30
}

lib/main.dart

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

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

final streamConfigProvider = StreamProvider.autoDispose<dynamic>((ref) {
  Stream<dynamic> getConfig() async* {
    final jsonContent = await rootBundle.loadString('lib/assets/config.json');
    yield json.decode(jsonContent);

    // 10秒待つ
    await Future.delayed(const Duration(seconds: 10));

    final jsonContent2 = await rootBundle.loadString('lib/assets/config2.json');
    yield json.decode(jsonContent2);
  }

  return getConfig();
});

class MyApp extends ConsumerWidget {
  // This widget is the root of your application.
  
  Widget build(BuildContext context, WidgetRef ref) {
    AsyncValue config = ref.watch(streamConfigProvider);

    return MaterialApp(
        home: Scaffold(
      appBar: AppBar(
        title: const Text('My First app'),
      ),
      body: config.when(
          loading: () => const CircularProgressIndicator(),
          error: (err, stack) => const Text('Error'),
          data: (config) {
            return Text("a: ${config['a']} / b: ${config['b']}");
          }),
    ));
  }
}

画面の表示直後

下記のようにテキストが表示されます。

a: 1 / b: 3

10秒待機後

下記のようにテキストが表示されます。

a: 1 / b: 30

参考


SHARE

Profile picture

Written by tamesuu