fileを読み込む (Flutter)

November 04, 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

ファイル準備

lib/assets/config.json

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

設定ファイルの修正

pubspec.yaml

flutter:
  ...
  assets:
    - lib/assets/config.json
  ...

検証コード

lib/main.dart

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:async';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  Future hoge() async {
    final content = await rootBundle.loadString('lib/assets/config.json');
    print(222);
    print(content);
  }

  // This widget is the root of your application.
  
  Widget build(BuildContext context) {
    hoge();

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

デバッグコンソール

I/flutter ( 3798): 222
I/flutter ( 3798): {
I/flutter ( 3798):   "a": 1,
I/flutter ( 3798):   "b": 3
I/flutter ( 3798): }

参考


SHARE

Profile picture

Written by tamesuu