在Flutter中,你可以使用Dio或http库来发送带有GET请求的参数。以下是两种方法的详细说明和示例代码。
Dio是一个强大的HTTP客户端,支持拦截器、全局配置、FormData、请求取消、文件下载、超时等。
首先,你需要在pubspec.yaml
文件中添加Dio依赖:
dependencies:
dio: ^4.0.0
然后运行flutter pub get
来安装依赖。
import 'package:dio/dio.dart';
void sendGetRequestWithDio() async {
try {
Dio dio = Dio();
Response response = await dio.get('https://example.com/api', queryParameters: {
'param1': 'value1',
'param2': 'value2',
});
print(response.data);
} catch (e) {
print('Error: $e');
}
}
http是Flutter官方提供的一个简单易用的HTTP客户端库。
同样,在pubspec.yaml
文件中添加http依赖:
dependencies:
http: ^0.13.3
然后运行flutter pub get
来安装依赖。
import 'package:http/http.dart' as http;
import 'dart:convert';
void sendGetRequestWithHttp() async {
try {
var url = Uri.parse('https://example.com/api')
.replace(queryParameters: {
'param1': 'value1',
'param2': 'value2',
});
var response = await http.get(url);
if (response.statusCode == 200) {
var jsonResponse = jsonDecode(response.body);
print(jsonResponse);
} else {
print('Request failed with status: ${response.statusCode}.');
}
} catch (e) {
print('Error: $e');
}
}
选择哪个库取决于你的具体需求和项目的复杂度。无论使用哪个库,都需要注意处理网络请求可能出现的异常情况,并确保在UI线程之外执行网络操作以避免阻塞UI。
领取专属 10元无门槛券
手把手带您无忧上云