null safety article
Contents
Make authenticated requests
ほとんどのWebサービスからデータをフェッチするには、認証を提供する必要があります。これを行うには多くの方法がありますが、おそらく最も一般的な方法はAuthorization
HTTPヘッダーを使用します。
このhttp
パッケージは、リクエストにヘッダーを追加するための便利な方法を提供します。
または、dart:ioライブラリのHttpHeaders
クラスを使用する方法もあります。
Future<http.Response> fetchAlbum() {
return http.get(
'https://jsonplaceholder.typicode.com/albums/1',
// Send authorization headers to the backend.
headers: {HttpHeaders.authorizationHeader: "Basic your_api_token_here"},
);
}
Complete example
import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:http/http.dart' as http; Future<Album> fetchAlbum() async { final response = await http.get( Uri.parse('https://jsonplaceholder.typicode.com/albums/1'), // Send authorization headers to the backend. headers: { HttpHeaders.authorizationHeader: 'Basic your_api_token_here', }, ); final responseJson = jsonDecode(response.body); return Album.fromJson(responseJson); } class Album { final int userId; final int id; final String title; Album({ required this.userId, required this.id, required this.title, }); factory Album.fromJson(Map<String, dynamic> json) { return Album( userId: json['userId'], id: json['id'], title: json['title'], ); } }
参考
https://flutter.dev/docs/cookbook/networking/authenticated-requests