实现思路
- 使用
http
库来发起网络请求,因为Flutter本身没有内置的网络请求功能。
- 定义一个函数,该函数返回一个
Future
,在函数内部发起网络请求。
- 使用
try-catch
块来捕获请求过程中可能出现的异常,在捕获到异常时显示错误提示。
- 在
Future
成功完成时,解析响应数据并返回。
关键代码片段
- 首先添加
http
依赖到pubspec.yaml
文件:
dependencies:
http: ^0.13.4
- 然后编写获取网络数据的函数:
import 'package:http/http.dart' as http;
import 'dart:convert';
Future<dynamic> fetchData() async {
try {
// 发起网络请求
var response = await http.get(Uri.parse('YOUR_API_URL'));
if (response.statusCode == 200) {
// 解析响应数据
return jsonDecode(response.body);
} else {
throw Exception('Failed to load data, status code: ${response.statusCode}');
}
} catch (e) {
// 捕获异常并显示错误提示
print('Error: $e');
return null;
}
}
- 在使用的地方调用该函数:
void main() async {
var data = await fetchData();
if (data != null) {
print('Data fetched successfully: $data');
} else {
print('Failed to fetch data');
}
}