Flutter HTTPリクエスト
このセクションでは、FlutterアプリでHTTPネットワークリクエストを行う方法を紹介します。GET、POSTリクエスト、およびJSONデータの処理を含みます。
HTTP依存関係を追加
pubspec.yaml に http パッケージを追加します:
dependencies: http: ^1.0.0
次に実行します:
$ flutter pub get
GETリクエストを送信
例:GETリクエスト
import 'dart:convert';
import 'package:http/http.dart' as http;
// シンプルなGETリクエスト
Future<void> fetchData() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));
if (response.statusCode == 200) {
// JSONデータを解析
final data = jsonDecode(response.body);
print('タイトル: ${data['title']}');
} else {
print('リクエスト失敗: ${response.statusCode}');
}
}
// パラメータ付きGETリクエスト
Future<void> searchData(String query) async {
final uri = Uri.parse('https://api.example.com/search')
.replace(queryParameters: {'q': query, 'page': '1'});
final response = await http.get(uri);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
print('結果: $data');
}
}
import 'package:http/http.dart' as http;
// シンプルなGETリクエスト
Future<void> fetchData() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));
if (response.statusCode == 200) {
// JSONデータを解析
final data = jsonDecode(response.body);
print('タイトル: ${data['title']}');
} else {
print('リクエスト失敗: ${response.statusCode}');
}
}
// パラメータ付きGETリクエスト
Future<void> searchData(String query) async {
final uri = Uri.parse('https://api.example.com/search')
.replace(queryParameters: {'q': query, 'page': '1'});
final response = await http.get(uri);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
print('結果: $data');
}
}
POSTリクエストを送信
例:POSTリクエスト
import 'dart:convert';
import 'package:http/http.dart' as http;
// POSTリクエスト - JSONデータを送信
Future<void> postData() async {
final uri = Uri.parse('https://jsonplaceholder.typicode.com/posts');
final response = await http.post(
uri,
headers: {
'Content-Type': 'application/json', // リクエストヘッダーを設定
},
body: jsonEncode({ // DartオブジェクトをJSON文字列に変換
'title': 'Flutterチュートリアル',
'body': 'Flutterネットワークリクエストを学ぶ',
'userId': 1,
}),
);
if (response.statusCode == 201) {
final data = jsonDecode(response.body);
print('作成成功: $data');
} else {
print('リクエスト失敗: ${response.statusCode}');
}
}
// POSTリクエスト - フォームデータを送信
Future<void> postFormData() async {
final uri = Uri.parse('https://example.com/api/login');
final response = await http.post(
uri,
body: {
'username': 'admin',
'password': '123456',
},
);
print('レスポンス: ${response.body}');
}
import 'package:http/http.dart' as http;
// POSTリクエスト - JSONデータを送信
Future<void> postData() async {
final uri = Uri.parse('https://jsonplaceholder.typicode.com/posts');
final response = await http.post(
uri,
headers: {
'Content-Type': 'application/json', // リクエストヘッダーを設定
},
body: jsonEncode({ // DartオブジェクトをJSON文字列に変換
'title': 'Flutterチュートリアル',
'body': 'Flutterネットワークリクエストを学ぶ',
'userId': 1,
}),
);
if (response.statusCode == 201) {
final data = jsonDecode(response.body);
print('作成成功: $data');
} else {
print('リクエスト失敗: ${response.statusCode}');
}
}
// POSTリクエスト - フォームデータを送信
Future<void> postFormData() async {
final uri = Uri.parse('https://example.com/api/login');
final response = await http.post(
uri,
body: {
'username': 'admin',
'password': '123456',
},
);
print('レスポンス: ${response.body}');
}
JSONデータの処理
例:JSONの解析
import 'dart:convert';
// データモデルを定義
class Article {
final int id;
final String title;
final String body;
final User user;
Article({
required this.id,
required this.title,
required this.body,
required this.user,
});
// JSONから解析
factory Article.fromJson(Map<String, dynamic> json) {
return Article(
id: json['id'],
title: json['title'],
body: json['body'],
user: User.fromJson(json['user']),
);
}
// JSONに変換
Map<String, dynamic> toJson() {
return {
'id': id,
'title': title,
'body': body,
'user': user.toJson(),
};
}
}
class User {
final int id;
final String name;
User({required this.id, required this.name});
factory User.fromJson(Map<String, dynamic> json) {
return User(id: json['id'], name: json['name']);
}
Map<String, dynamic> toJson() {
return {'id': id, 'name': name};
}
}
// 使用例
void parseJson() {
final jsonString = '''
{
"id": 1,
"title": "Flutterチュートリアル",
"body": "Flutterを学ぶ",
"user": {"id": 1, "name": "張三"}
}
''';
// JSON文字列を解析
final Map<String, dynamic> json = jsonDecode(jsonString);
final article = Article.fromJson(json);
print('記事ID: ${article.id}');
print('著者: ${article.user.name}');
}
// データモデルを定義
class Article {
final int id;
final String title;
final String body;
final User user;
Article({
required this.id,
required this.title,
required this.body,
required this.user,
});
// JSONから解析
factory Article.fromJson(Map<String, dynamic> json) {
return Article(
id: json['id'],
title: json['title'],
body: json['body'],
user: User.fromJson(json['user']),
);
}
// JSONに変換
Map<String, dynamic> toJson() {
return {
'id': id,
'title': title,
'body': body,
'user': user.toJson(),
};
}
}
class User {
final int id;
final String name;
User({required this.id, required this.name});
factory User.fromJson(Map<String, dynamic> json) {
return User(id: json['id'], name: json['name']);
}
Map<String, dynamic> toJson() {
return {'id': id, 'name': name};
}
}
// 使用例
void parseJson() {
final jsonString = '''
{
"id": 1,
"title": "Flutterチュートリアル",
"body": "Flutterを学ぶ",
"user": {"id": 1, "name": "張三"}
}
''';
// JSON文字列を解析
final Map<String, dynamic> json = jsonDecode(jsonString);
final article = Article.fromJson(json);
print('記事ID: ${article.id}');
print('著者: ${article.user.name}');
}
エラー処理
例:完全なネットワークリクエストのサンプル
import 'dart:convert';
import 'package:http/http.dart' as http;
class ApiService {
// ベースURL
static const String baseUrl = 'https://jsonplaceholder.typicode.com';
// 汎用GETリクエストメソッド
static Future<dynamic> get(String endpoint) async {
try {
final response = await http.get(
Uri.parse('$baseUrl/$endpoint'),
);
return _handleResponse(response);
} catch (e) {
throw ApiException('ネットワークエラー: $e');
}
}
// 汎用POSTリクエストメソッド
static Future<dynamic> post(
String endpoint,
Map<String, dynamic> data,
) async {
try {
final response = await http.post(
Uri.parse('$baseUrl/$endpoint'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode(data),
);
return _handleResponse(response);
} catch (e) {
throw ApiException('ネットワークエラー: $e');
}
}
// レスポンスを処理
static dynamic _handleResponse(http.Response response) {
if (response.statusCode >= 200 && response.statusCode < 300) {
// 成功レスポンス
if (response.body.isEmpty) {
return null;
}
return jsonDecode(response.body);
} else if (response.statusCode == 404) {
throw ApiException('リソースが見つかりません', statusCode: 404);
} else if (response.statusCode >= 500) {
throw ApiException('サーバーエラー', statusCode: response.statusCode);
} else {
throw ApiException(
'リクエスト失敗',
statusCode: response.statusCode,
);
}
}
}
// カスタム例外クラス
class ApiException implements Exception {
final String message;
final int? statusCode;
ApiException(this.message, {this.statusCode});
@override
String toString() => 'ApiException: $message (status: $statusCode)';
}
// 使用例
Future<void> fetchArticles() async {
try {
final articles = await ApiService.get('posts');
print('${articles.length} 件の記事を取得しました');
} on ApiException catch (e) {
print('APIエラー: $e');
}
}
import 'package:http/http.dart' as http;
class ApiService {
// ベースURL
static const String baseUrl = 'https://jsonplaceholder.typicode.com';
// 汎用GETリクエストメソッド
static Future<dynamic> get(String endpoint) async {
try {
final response = await http.get(
Uri.parse('$baseUrl/$endpoint'),
);
return _handleResponse(response);
} catch (e) {
throw ApiException('ネットワークエラー: $e');
}
}
// 汎用POSTリクエストメソッド
static Future<dynamic> post(
String endpoint,
Map<String, dynamic> data,
) async {
try {
final response = await http.post(
Uri.parse('$baseUrl/$endpoint'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode(data),
);
return _handleResponse(response);
} catch (e) {
throw ApiException('ネットワークエラー: $e');
}
}
// レスポンスを処理
static dynamic _handleResponse(http.Response response) {
if (response.statusCode >= 200 && response.statusCode < 300) {
// 成功レスポンス
if (response.body.isEmpty) {
return null;
}
return jsonDecode(response.body);
} else if (response.statusCode == 404) {
throw ApiException('リソースが見つかりません', statusCode: 404);
} else if (response.statusCode >= 500) {
throw ApiException('サーバーエラー', statusCode: response.statusCode);
} else {
throw ApiException(
'リクエスト失敗',
statusCode: response.statusCode,
);
}
}
}
// カスタム例外クラス
class ApiException implements Exception {
final String message;
final int? statusCode;
ApiException(this.message, {this.statusCode});
@override
String toString() => 'ApiException: $message (status: $statusCode)';
}
// 使用例
Future<void> fetchArticles() async {
try {
final articles = await ApiService.get('posts');
print('${articles.length} 件の記事を取得しました');
} on ApiException catch (e) {
print('APIエラー: $e');
}
}
その他の拡張実際のアプリでは、ネットワークリクエストをサービス層にカプセル化し、エラー処理、ローディング状態、キャッシュロジックを統一して扱うことをお勧めします。