1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Flutterでhttpパッケージを使ってAPI通信を行う方法(毎日Flutter生活15日目)

Posted at

こんにちは!tatata-keshiです:smiley:

Flutterアプリ開発では、外部APIと通信してデータを取得・送信する場面が頻繁に登場します。
この記事では、Flutter公式に近い立ち位置で使われている http パッケージ を用いて、

  • GET / POST 通信の基本
  • JSONの扱い方
  • 実践的な実装例
  • エラーハンドリング

までを順を追って解説します。

http パッケージとは?

http は、Flutter / Dartで シンプルにHTTP通信を行うためのパッケージ です。

特徴:

  • 学習コストが低い
  • 小〜中規模アプリに最適
  • REST APIとの通信に向いている

1. パッケージのインストール

まずは pubspec.yamlhttp を追加します。

dependencies:
  flutter:
    sdk: flutter
  http: ^1.6.0

パッケージを取得します。

flutter pub get

2. 基本的な使い方(GET通信)

シンプルなGETリクエスト

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

Future<void> fetchData() async {
  final response = await http.get(
    Uri.parse('https://jsonplaceholder.typicode.com/posts/1'),
  );

  if (response.statusCode == 200) {
    print(response.body);
  } else {
    throw Exception('Failed to load data');
  }
}

ポイント

  • Uri.parse() を必ず使う
  • response.statusCode で成功判定
  • response.bodyString(JSON文字列)

3. JSONをMapに変換する

APIレスポンスは通常JSONなので、dart:convert を使って変換します。

import 'dart:convert';

final data = jsonDecode(response.body);

例:

Future<Map<String, dynamic>> fetchPost() async {
  final response = await http.get(
    Uri.parse('https://jsonplaceholder.typicode.com/posts/1'),
  );

  if (response.statusCode == 200) {
    return jsonDecode(response.body);
  } else {
    throw Exception('Failed to load post');
  }
}

4. POST通信の方法

JSONを送信するPOSTリクエスト

Future<void> createPost() async {
  final response = await http.post(
    Uri.parse('https://jsonplaceholder.typicode.com/posts'),
    headers: {
      'Content-Type': 'application/json',
    },
    body: jsonEncode({
      'title': 'Flutter',
      'body': 'HTTP POST example',
      'userId': 1,
    }),
  );

  if (response.statusCode == 201) {
    print('Post created');
  } else {
    throw Exception('Failed to create post');
  }
}

よくある注意点

  • Content-Type: application/json を忘れない
  • bodyjsonEncode する

5. モデルクラスを使った実装(実践)

モデルクラス定義

class Post {
  final int id;
  final String title;
  final String body;

  Post({
    required this.id,
    required this.title,
    required this.body,
  });

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      id: json['id'],
      title: json['title'],
      body: json['body'],
    );
  }
}

API通信でモデルに変換

Future<Post> fetchPost() async {
  final response = await http.get(
    Uri.parse('https://jsonplaceholder.typicode.com/posts/1'),
  );

  if (response.statusCode == 200) {
    return Post.fromJson(jsonDecode(response.body));
  } else {
    throw Exception('Failed to load post');
  }
}

6. UIで非同期通信を扱う(FutureBuilder)

FutureBuilder<Post>(
  future: fetchPost(),
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting) {
      return const CircularProgressIndicator();
    } else if (snapshot.hasError) {
      return Text('Error: ${snapshot.error}');
    } else {
      final post = snapshot.data!;
      return Column(
        children: [
          Text(post.title),
          Text(post.body),
        ],
      );
    }
  },
)

7. ヘッダー・認証情報を付与する

final response = await http.get(
  Uri.parse(url),
  headers: {
    'Authorization': 'Bearer YOUR_TOKEN',
    'Accept': 'application/json',
  },
);

※ APIキーは flutter_dotenv などで管理するのがおすすめです。

8. エラーハンドリングの考え方

最低限、以下は分けて扱いましょう。

if (response.statusCode >= 200 && response.statusCode < 300) {
  // 成功
} else if (response.statusCode == 401) {
  // 認証エラー
} else {
  // その他エラー
}

また、通信失敗(圏外など)には try-catch が必須です。

try {
  final response = await http.get(uri);
} catch (e) {
  // ネットワークエラー
}

9. よくあるハマりポイント

  • await を付け忘れる
  • Uri.parse() を使っていない
  • JSONの型不一致(int / String)
  • UI側でFutureを毎回生成してしまう

まとめ

  • http パッケージはシンプルで扱いやすい
  • GET / POST の基本を押さえれば十分実用的
  • JSON → モデル変換が重要
  • 小〜中規模アプリに最適な選択肢

FlutterでのAPI通信の第一歩として、
まずは http パッケージをしっかり使いこなせるようになるのがおすすめです 🚀

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?