网络$http
从网络上获取数据
步骤:
-
添加
http
package。 -
使用
http
package 进行网络请求。 -
将返回的响应转换成一个自定义的 Dart 对象。
-
使用 Flutter 对数据进行获取和展示。
-
添加
http
package要将
http
package 添加到依赖中,运行flutter pub add
命令:flutter pub add http
导入 http package
import 'package:http/http.dart' as http;
部署 Android,编辑
AndroidManifest.xml
文件,添加 Internet 权限。
<!-- Required to fetch data from the internet. -->
<uses-permission android:name="android.permission.INTERNET" />
- 进行网络请求
Future<http.Response> fetchAlbum() {
return http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
}
Future
是 Dart 用来处理异步操作的一个核心类,它通常代表一个可能的值或者将来或许会用到的错误。http.Response
类包含成功的 http 请求接收到的数据。
- 将返回的响应转换成一个自定义的 Dart 对象
创建一个 Album
类
首先,创建一个包含网络请求返回数据的 Album
类,而且这个类还需要一个可以利用 json 创建 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.'),
};
}
}
将 http.Response
转换成 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');
}
}
- 获取数据
class _MyAppState extends State<MyApp> {
late Future<Album> futureAlbum;
void initState() {
super.initState();
futureAlbum = fetchAlbum();
}
// ···
}
显示数据
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();
},
)
发起 HTTP 认证授权请求
添加 Authorization Headers
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',
},
);