透過網際網路更新資料
對於大多數應用程式來說,透過網際網路更新資料是必要的。http 包已經涵蓋了這一點!
本示例將採取以下步驟
- 新增 `http` 包。
- 使用
http包透過網際網路更新資料。 - 將響應轉換為自定義 Dart 物件。
- 從網際網路獲取資料。
- 根據使用者輸入更新現有
title。 - 更新並在螢幕上顯示響應。
1. 新增 `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 包透過網際網路更新資料
#本食譜介紹瞭如何使用 http.put() 方法將專輯標題更新到 JSONPlaceholder。
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}),
);
}http.put() 方法返回一個包含 Response 的 Future。
Future是 Dart 中用於處理非同步操作的核心類。Future物件表示將來某個時間可用的潛在值或錯誤。- `http.Response` 類包含成功 http 呼叫接收到的資料。
updateAlbum()方法接受一個引數title,該引數傳送到伺服器以更新Album。
3. 將 http.Response 轉換為自定義 Dart 物件
#雖然進行網路請求很簡單,但直接處理原始的 `Future<http.Response>` 並不是很方便。為了簡化開發,請將 `http.Response` 轉換為 Dart 物件。
建立 Album 類
#首先,建立一個 `Album` 類來包含網路請求中的資料。它包含一個工廠建構函式,用於從 JSON 建立 `Album` 物件。
使用 模式匹配 轉換 JSON 只是其中一種選擇。更多資訊,請參閱關於 JSON 和序列化 的完整文章。
class Album {
final int id;
final String title;
const Album({required this.id, required this.title});
factory Album.fromJson(Map<String, dynamic> json) {
return switch (json) {
{'id': int id, 'title': String title} => Album(id: id, title: title),
_ => throw const FormatException('Failed to load album.'),
};
}
}將 `http.Response` 轉換為 `Album` 物件
#現在,使用以下步驟更新 updateAlbum() 函式,使其返回 Future<Album>
- 使用 `dart:convert` 包將響應體轉換為 JSON `Map`。
- 如果伺服器返回狀態碼為 200 的
UPDATED響應,則使用fromJson()工廠方法將 JSONMap轉換為Album。 - 如果伺服器未返回狀態碼為 200 的
UPDATED響應,則丟擲異常。(即使在“404 Not Found”伺服器響應的情況下,也要丟擲異常。不要返回null。這在檢查snapshot中的資料時很重要,如下所示。)
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',
},
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) as Map<String, dynamic>);
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to update album.');
}
}太棒了!現在你有一個更新專輯標題的函數了。
從網際網路獲取資料
#在更新資料之前,先從網際網路獲取資料。有關完整示例,請參閱獲取資料食譜。
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');
}
}理想情況下,你將在 initState 期間使用此方法設定 _futureAlbum,以從網際網路獲取資料。
4. 根據使用者輸入更新現有標題
#建立一個 TextField 以輸入標題,以及一個 ElevatedButton 以更新伺服器上的資料。還要定義一個 TextEditingController 以從 TextField 讀取使用者輸入。
當按下 ElevatedButton 時,_futureAlbum 被設定為 updateAlbum() 方法返回的值。
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8),
child: TextField(
controller: _controller,
decoration: const InputDecoration(hintText: 'Enter Title'),
),
),
ElevatedButton(
onPressed: () {
setState(() {
_futureAlbum = updateAlbum(_controller.text);
});
},
child: const Text('Update Data'),
),
],
);按下 **Update Data** 按鈕後,網路請求將 TextField 中的資料作為 PUT 請求傳送到伺服器。_futureAlbum 變數將在下一步中使用。
5. 在螢幕上顯示響應
#要在螢幕上顯示資料,請使用 FutureBuilder 小部件。FutureBuilder 小部件隨 Flutter 提供,可以輕鬆處理非同步資料來源。你必須提供兩個引數
- 要處理的
Future。在此情況下,為updateAlbum()函式返回的 Future。 - 一個 `builder` 函式,它根據 `Future` 的狀態(載入中、成功或錯誤)告訴 Flutter 要渲染什麼。
請注意,snapshot.hasData 僅在 snapshot 包含非空資料值時才返回 true。這就是為什麼 updateAlbum 函式即使在“404 Not Found”伺服器響應的情況下也應該丟擲異常。如果 updateAlbum 返回 null,則 CircularProgressIndicator 將無限期顯示。
FutureBuilder<Album>(
future: _futureAlbum,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data!.title);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return const CircularProgressIndicator();
},
);完整示例
#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');
}
}
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',
},
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) as Map<String, dynamic>);
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to update album.');
}
}
class Album {
final int id;
final String title;
const Album({required this.id, required this.title});
factory Album.fromJson(Map<String, dynamic> json) {
return switch (json) {
{'id': int id, 'title': String title} => Album(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() {
return _MyAppState();
}
}
class _MyAppState extends State<MyApp> {
final TextEditingController _controller = TextEditingController();
late Future<Album> _futureAlbum;
@override
void initState() {
super.initState();
_futureAlbum = fetchAlbum();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Update Data Example',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
),
home: Scaffold(
appBar: AppBar(title: const Text('Update Data Example')),
body: Container(
alignment: Alignment.center,
padding: const EdgeInsets.all(8),
child: FutureBuilder<Album>(
future: _futureAlbum,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasData) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(snapshot.data!.title),
TextField(
controller: _controller,
decoration: const InputDecoration(
hintText: 'Enter Title',
),
),
ElevatedButton(
onPressed: () {
setState(() {
_futureAlbum = updateAlbum(_controller.text);
});
},
child: const Text('Update Data'),
),
],
);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
}
return const CircularProgressIndicator();
},
),
),
),
);
}
}