flutter：APIから返ってきたJSONレスポンスをページに表示する

# やりたいこと

無料で使える「郵便番号検索API」
http://zipcloud.ibsnet.co.jp/doc/api
を使って、JSONで返ってくる下記パラメータ

https://zipcloud.ibsnet.co.jp/api/search?zipcode=1620055

```json
{
  "message": null,
  "results": [
    {
      "address1": "東京都",
      "address2": "新宿区",
      "address3": "余丁町",
      "kana1": "ﾄｳｷｮｳﾄ",
      "kana2": "ｼﾝｼﾞｭｸｸ",
      "kana3": "ﾖﾁｮｳﾏﾁ",
      "prefcode": "13",
      "zipcode": "1620055"
    }
  ],
  "status": 200
}
```

を、アプリで取得してページに表示する。

# httpパッケージを有効化する。

https://qiita.com/kenichiro-yamato/items/ce7d77e9c733c24024d8
の手順にて取り込む。

# import

```dart
import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
```




# MyApp

```dart

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

```


# _MyAppState

```dart
class _MyAppState extends State<MyApp> {
  Future<ApiResults> futureApiResults;
  @override
  void initState() {
    super.initState();
    futureApiResults = fetchApiResults();
  }
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'APIから返ってきたJSONレスポンスをページに表示する',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Api JSON Response Sample'),
        ),
        body: Center(
          child: FutureBuilder<ApiResults>(
            future: futureApiResults,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Text(
                  snapshot.data.status.toString() 
                  + " : " 
                  + snapshot.data.results[0]['address1'] 
                  + snapshot.data.results[0]['address2']
                  + snapshot.data.results[0]['address3']
                  );
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}
```




# 住所クラスを実装する。

APIから取得するパラメータに対応させる。

```dart

class ApiResults {
  final String message;
  final results;
  final int status;

  ApiResults({
    this.message,
    this.results,
    this.status
  });

  factory ApiResults.fromJson(Map<String, dynamic> json) {
    return ApiResults(
      message: json['message'],
      results: json['results'],
      status: json['status'],
    );
  }
}
```

# APIを呼び出す。

非同期でAPIを叩いてレスポンスを取得する。

```dart
Future<ApiResults> fetchApiResults() async {
  final response = await http.get('https://zipcloud.ibsnet.co.jp/api/search?zipcode=1620055');
  if (response.statusCode == 200) {
    return ApiResults.fromJson(json.decode(response.body));
  } else {
    throw Exception('Failed to load API params');
  }
}
```

# 完成形 main.dart

```dart
import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;


void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Future<ApiResults> futureApiResults;
  @override
  void initState() {
    super.initState();
    futureApiResults = fetchApiResults();
  }
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'APIから返ってきたJSONレスポンスをページに表示する',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Api JSON Response Sample'),
        ),
        body: Center(
          child: FutureBuilder<ApiResults>(
            future: futureApiResults,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Text(
                  snapshot.data.status.toString() 
                  + " : " 
                  + snapshot.data.results[0]['address1'] 
                  + snapshot.data.results[0]['address2']
                  + snapshot.data.results[0]['address3']
                  );
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}

class ApiResults {
  final String message;
  final results;
  final int status;

  ApiResults({
    this.message,
    this.results,
    this.status
  });

  factory ApiResults.fromJson(Map<String, dynamic> json) {
    return ApiResults(
      message: json['message'],
      results: json['results'],
      status: json['status'],
    );
  }
}

Future<ApiResults> fetchApiResults() async {
  final response = await http.get('https://zipcloud.ibsnet.co.jp/api/search?zipcode=1620055');
  if (response.statusCode == 200) {
    return ApiResults.fromJson(json.decode(response.body));
  } else {
    throw Exception('Failed to load API params');
  }
}


```


![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/75451/88906fd9-6275-69e0-35c5-6b9b276f701f.png)