Help us understand the problem. What is going on with this article?

【Flutter】ローカルJSONファイル読み込み(HTTP通信のテストをテストする時などに使う)

開発環境
⭐️Macbook Pro
⭐️Flutter
(Flutter 1.12.13+hotfix.7)
⭐️Android Stuido 3.5.3

↓↓ローカルJSONファイル読み込み 完成内容
スクリーンショット 2020-02-16 17.47.10.png

1.Jsonファイルを用意する

「api_name.json」

api_name.json
{
  "count": 5,
  "address": "Fukuoka",
  "main": null,
  "categorydata": [
    {
      "kapibara_id": "100",
      "kapibara_Name": "カピバラさん",
      "kapibara_Old": 10
    },
    {
      "kapibara_id": "101",
      "kapibara_Name": "ホワイトさん",
      "kapibara_Old": 20
    },
    {
      "kapibara_id": "102",
      "kapibara_Name": "仔カピバラさん",
      "kapibara_Old": 30
    },
    {
      "kapibara_id": "103",
      "kapibara_Name": "ひだまりさん",
      "kapibara_Old": 40
    },
    {
      "kapibara_id": "104",
      "kapibara_Name": "仔カピ兄",
      "kapibara_Old": 50
    },
    {
      "kapibara_id": "105",
      "kapibara_Name": "カピバラ105",
      "kapibara_Old": 60
    },
    {
      "kapibara_id": "106",
      "kapibara_Name": "カピバラ106",
      "kapibara_Old": 70
    }
  ]
}

2.JSONファイルをプロジェクタに配置する

json - api_name.json
スクリーンショット 2020-02-16 17.56.40.png

3.「pubspec.yaml」に「json」フォルダ配下を読みとる記述をする
スクリーンショット 2020-02-16 17.58.54.png

  assets:
    - json/
main.dart
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:async';
import 'dart:convert';
import 'package:flutter/services.dart' show rootBundle;

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'non Local JSON Test"',
      theme: new ThemeData(
        primarySwatch: Colors.pink,
      ),
      home: new LocalJsonData(),
    );
  }
}


class LocalJsonData extends StatefulWidget {
  @override
  LocalJsonDataState createState() => new LocalJsonDataState();
}

class LocalJsonDataState extends State<LocalJsonData> {
  List _data; //データ


  /*
   * ローカルJSONファイル読み込みテスト用「api_name.json」
   */
  Future<String> _loadAVaultAsset() async {
    return await rootBundle.loadString('json/api_name.json');
  }

  /*
   * ローカルJSON データセット
   */
  Future getLocalTestJSONData() async {
    String jsonString = await _loadAVaultAsset();
    setState(() {
      final jsonResponse = json.decode(jsonString);
      print("### getLocalTestJSONData:" + jsonResponse.toString());
      _data = jsonResponse['categorydata'];
    });
  }



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("non JSON Test"),
      ),
      //Create a Listview and load the data when available
      body: ListView.builder(
          itemCount: _data == null ? 0 : _data.length,
          itemBuilder: (BuildContext context, int index) {
            return Container(
              child: Center(
                  child: Column(
                    // Stretch the cards in horizontal axis
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: <Widget>[
                      Card(
                        child: Container(
                          child: ListTile(
                            leading: null,
                            title: Text(
                                "kapibara_id:" + _data[index]['kapibara_id'].toString(),
                                style: TextStyle(
                                    fontSize: 20.0, color: Colors.amber[900])
                            ),
                            subtitle: Text(
                                "kapibara_Name:" + _data[index]['kapibara_Name'],
                                style: TextStyle(fontSize: 20.0, color: Colors.amber[900])
                            ),
                            onTap: () {
                              /* react to the tile being tapped */ },
                          ),
                          // added padding
                          padding: const EdgeInsets.all(15.0),
                        ),
                      )
                    ],
                  )),
            );
          }),
    );
  }

  @override
  void initState() {
    super.initState();

    //ローカルJSON
    this.getLocalTestJSONData();
  }

}


Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした