RiverpodのFutureProviderを使う (Flutter)

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

FutureProviderを使ってみる

ファイル準備

lib/assets/config.json

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

検証コード

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 configProvider = FutureProvider<Map<String, Object?>>((ref) async {
  final jsonContent = await rootBundle.loadString('lib/assets/config.json');
  return json.decode(jsonContent) as Map<String, Object?>;
});

class MyApp extends ConsumerWidget {
  // This widget is the root of your application.
  
  Widget build(BuildContext context, WidgetRef ref) {
    AsyncValue<Map<String, Object?>> config = ref.watch(configProvider);

    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']}");
          }),
    ));
  }
}

参考


SHARE

Profile picture

Written by tamesuu