從網際網路獲取資料
如何使用 http 包透過網際網路獲取資料。
對於大多數應用程式來說,從網際網路獲取資料是必要的。幸運的是,Dart 和 Flutter 提供了諸如 http 包之類的工具來完成這項工作。
本示例將採取以下步驟
- 新增 `http` 包。
- 使用
http包發起網路請求。 - 將響應轉換為自定義 Dart 物件。
- 使用 Flutter 獲取和顯示資料。
1. 新增 `http` 包
#http 包提供了從網際網路獲取資料的最簡單方法。
要將 http 包新增為依賴項,請執行 flutter pub add。
flutter pub add http
匯入 http 包。
import 'package:http/http.dart' as http;
如果你部署到 Android,請編輯 `AndroidManifest.xml` 檔案以新增網際網路許可權。
<!-- Required to fetch data from the internet. -->
<uses-permission android:name="android.permission.INTERNET" />
同樣,如果你部署到 macOS,請編輯 `macos/Runner/DebugProfile.entitlements` 和 `macos/Runner/Release.entitlements` 檔案以包含網路客戶端授權。
<!-- Required to fetch data from the internet. -->
<key>com.apple.security.network.client</key>
<true/>
2. 發起網路請求
#本教程介紹如何使用 http 包從 JSONPlaceholder 獲取一個示例專輯,並使用 http.get() 方法。
Future<http.Response> fetchAlbum() {
return http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
}
http.get() 方法返回一個包含 Response 的 Future。
-
Future是 Dart 中用於處理非同步操作的核心類。Future 物件表示將來某個時間點可用或可能發生的錯誤的值。 - `http.Response` 類包含成功 http 呼叫接收到的資料。
3. 將響應轉換為自定義 Dart 物件
#雖然進行網路請求很簡單,但直接處理原始的 `Future<http.Response>` 並不是很方便。為了簡化開發,請將 `http.Response` 轉換為 Dart 物件。
建立一個 Album 類
#
首先,建立一個 `Album` 類來包含網路請求中的資料。它包含一個工廠建構函式,用於從 JSON 建立 `Album` 物件。
使用 模式匹配 進行 JSON 轉換隻是一種選擇。有關更多資訊,請參閱關於 JSON 和序列化 的完整文章。
class Album {
final int userId;
final int id;
final String title;
const Album({required this.userId, required this.id, required this.title});
factory Album.fromJson(Map<String, dynamic> json) {
return switch (json) {
{'userId': int userId, 'id': int id, 'title': String title} => Album(
userId: userId,
id: id,
title: title,
),
_ => throw const FormatException('Failed to load album.'),
};
}
}
將 `http.Response` 轉換為 `Album` 物件
#現在,使用以下步驟更新 fetchAlbum() 函式,使其返回一個 Future<Album>
- 使用 `dart:convert` 包將響應體轉換為 JSON `Map`。
- 如果伺服器返回一個狀態碼為 200 的 OK 響應,則使用
fromJson()工廠方法將 JSONMap轉換為一個Album。 - 如果伺服器沒有返回一個狀態碼為 200 的 OK 響應,則丟擲一個異常。(即使在伺服器響應為“404 Not Found”的情況下,也應該丟擲一個異常。不要返回
null。這在檢查snapshot中的資料時非常重要,如下所示。)
Future<Album> fetchAlbum() async {
final response = await http.get(
Uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
);
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
太棒了!現在你已經擁有一個從網際網路獲取專輯的函數了。
4. 獲取資料
#在 initState() 或 didChangeDependencies() 方法中呼叫 fetchAlbum() 方法。
initState() 方法只會被呼叫一次,之後就不會再被呼叫。如果您希望根據 InheritedWidget 的變化重新載入 API,請將呼叫放入 didChangeDependencies() 方法中。有關更多詳細資訊,請參閱 State。
class _MyAppState extends State<MyApp> {
late Future<Album> futureAlbum;
@override
void initState() {
super.initState();
futureAlbum = fetchAlbum();
}
// ···
}
這個 Future 在下一步中會被使用。
5. 顯示資料
#要在螢幕上顯示資料,請使用 FutureBuilder 元件。FutureBuilder 元件隨 Flutter 一起提供,可以輕鬆地處理非同步資料來源。
您必須提供兩個引數
- 您想要處理的
Future。在這種情況下,是fetchAlbum()函式返回的 future。 - 一個 `builder` 函式,它根據 `Future` 的狀態(載入中、成功或錯誤)告訴 Flutter 要渲染什麼。
請注意,snapshot.hasData 僅在快照包含非空資料值時才返回 true。
由於 fetchAlbum 只能返回非空值,因此即使在伺服器響應為“404 Not Found”的情況下,該函式也應該丟擲一個異常。丟擲異常會將 snapshot.hasError 設定為 true,這可用於顯示錯誤訊息。
否則,將顯示載入指示器。
FutureBuilder<Album>(
future: futureAlbum,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data!.title);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
)
為什麼要在 initState() 中呼叫 fetchAlbum()?
#雖然很方便,但不建議將 API 呼叫放在 build() 方法中。
Flutter 會在每次需要更改檢視中的任何內容時呼叫 build() 方法,而這種情況發生的頻率很高。如果將 fetchAlbum() 方法放在 build() 內部,它將在每次重建時被重複呼叫,從而導致應用程式變慢。
將 fetchAlbum() 的結果儲存在狀態變數中,可以確保 Future 只執行一次,然後快取以供後續重建使用。
測試
#有關如何測試此功能的更多資訊,請參閱以下教程
完整示例
#import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<Album> fetchAlbum() async {
final response = await http.get(
Uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
);
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
class Album {
final int userId;
final int id;
final String title;
const Album({required this.userId, required this.id, required this.title});
factory Album.fromJson(Map<String, dynamic> json) {
return switch (json) {
{'userId': int userId, 'id': int id, 'title': String title} => Album(
userId: userId,
id: id,
title: title,
),
_ => throw const FormatException('Failed to load album.'),
};
}
}
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late Future<Album> futureAlbum;
@override
void initState() {
super.initState();
futureAlbum = fetchAlbum();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
),
home: Scaffold(
appBar: AppBar(title: const Text('Fetch Data Example')),
body: Center(
child: FutureBuilder<Album>(
future: futureAlbum,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data!.title);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
),
),
),
);
}
}