Blog スタッフブログ

Flutter システム開発 ひとくちコードスニペット

[Flutter]Flutterでの簡単JSON API通信実装

こんにちは、株式会社MIXシステム開発担当のBloomです。

今回はFlutterで利用できるJSONデータを受け取るAPIの簡単な実装を紹介します。まずはパッケージのインストールから行いましょう。

dart pub add http

では、API通信を行うためのクラスを実装してみましょう。まずはモデルクラスから実装します。

class ApiModel {
  final int result;
  final List<ChildModel> children;

  ApiModel({
    required this.result,
    required this.children,
  });
  factory ApiModel(Map<String, dynamic> json) {
    int result = json["result"];

    List<ChildModel> children = (json['children'] as List)
        .map((json) => ChildModel(json))
        .toList();

    return ApiModel(result: result, children: children);
  }
}


class ChildModel {
  final int id;
  final String name;

  NumberModel({
    required this.id,
    required this.name,
  });

  factory ChildModel.fromJson(Map<String, dynamic> json) {
    int id = json["id"];
    String name = json["name"];
    return ChildModel(
        id: id, name: name);
  }
}

では、通信処理部を実装してみましょう。

import 'package:http/http.dart' as http;
class ApiConnection {
  static Future<ApiModel> fetch(int id) async {
    final res = await http.post(
      Uri.parse('https:// ... /execute'),
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: {
        'id': id,
      },
    );
    if (res.statusCode == 200) {
      debugPrint(res.body);
      return ApiModel.fromJson(jsonDecode(res.body));
    } else {
      debugPrint(res.body);
      throw Exception('Api execute Failed');
    }
  }
}

たったこれだけでJSON文字列を返すAPIへのアクセス処理を実装できました。良かったですね。


Warning: Undefined array key 0 in /home/fl0uhem6u4/mixltd.jp/public_html/cms/wp-content/themes/mix_theme/pagination-single.php on line 3

Warning: Attempt to read property "cat_ID" on null in /home/fl0uhem6u4/mixltd.jp/public_html/cms/wp-content/themes/mix_theme/pagination-single.php on line 3