この章ではアプリケーション開発で避けては通れない API 通信について解説していきます。
http
パッケージ
Flutter から API 通信を行うにはhttp
パッケージという外部パッケージを活用します。
API 通信をサポートするパッケージでは他にもdio
など多機能で人気なパッケージがありますので、気になる方は試してみてください
パッケージの導入
- パッケージの追加
$ flutter pub add http
- 使用するファイルで
import
import 'package:http/http.dart' as http;
基本的な使い方
基本的な使い方をPUT
メソッドを例に見ていきましょう
全体像
Future<Album> updateAlbum(String title) async {
final response = await http.put(
Uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
HttpHeaders.authorizationHeader: 'Bearer $token',
},
body: jsonEncode(<String, String>{
'title': title,
}),
);
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return Album.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to update album.');
}
}
エンドポイントの指定
全てのメソッドについて第一引数で Uri にパースしたエンドポイントの url を渡す必要があります。
Uri.parse
メソッドに url のパスを指定するだけです。
Uri.parse('https://jsonplaceholder.typicode.com/albums/1')
header 要素の追加
メソッドのheader
パラメータに Map
型で header 要素を渡すことが出来ます。'Content-Type'
のように文字列で指定しても良いですし、http
パッケージでHttpHeaders
というクラスによく使う文字列が定義されているのでそちらを使っても構いません。
authorization
を必要とするような場合もこちらに追記し含めることが出来ます。
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
HttpHeaders.authorizationHeader: 'Bearer $token',
}
body 要素の追加
メソッドのbody
パラメータに更新するデータを渡す事で body 要素に追加する事ができます。
後述のjsonEncode
メソッドを使って、json 化した値を渡します。
body: jsonEncode(<String, String>{
'title': title,
}),
レスポンスのハンドリング
レスポンスはhttp
パッケージに定義されたResponse
型として返却されます。statusCode
、headers
、body
などの情報が含められています。
これらの値を元にハンドリング処理を実装していきます。
if (response.statusCode == 200) {
return response.body;
} else {
throw Exception('Failed to update album.');
}
各種メソッド
基本的にはメソッド名が違うだけでその他の指定項目などは変わりません。
GET
Future<http.Response> fetchAlbum() {
return http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
}
POST
Future<http.Response> createAlbum(String title) {
return http.post(
Uri.parse('https://jsonplaceholder.typicode.com/albums'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'title': title,
}),
);
}
PUT
Future<http.Response> updateAlbum(String title) {
return http.put(
Uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'title': title,
}),
);
}
PATCH
Future<http.Response> updateUserId(String userId) {
return http.patch(
Uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'userId': userId,
}),
);
}
DELETE
Future<http.Response> deleteAlbum(String id) async {
final http.Response response = await http.delete(
Uri.parse('https://jsonplaceholder.typicode.com/albums/$id'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
);
return response;
}
まとめ
今回使ったhttp
パッケージは機能はシンプルですが、記述もシンプルで使いやすかったかと思います。
さてここまで Flutter でアプリ開発を行うのに必要な知識は揃いました。次章よりこれまでに学んだ知識を使って実際にアプリを作ってみましょう!🚀