面试题答案
一键面试- 添加依赖:
在
pubspec.yaml
文件中添加http
插件依赖:
dependencies:
http: ^0.13.4
然后运行flutter pub get
安装依赖。
- 封装GET请求:
import 'package:http/http.dart' as http;
import 'dart:convert';
Future<dynamic> getRequest(String url) async {
try {
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
return json.decode(response.body);
} else {
throw Exception('Failed to load data');
}
} catch (e) {
throw Exception('Error occurred during request: $e');
}
}
- 使用封装的请求:
void main() async {
try {
var result = await getRequest('https://example.com/api/data');
print(result);
} catch (e) {
print('Error: $e');
}
}
在上述代码中:
- 首先添加
http
插件依赖并安装。 - 然后定义
getRequest
函数,在函数内部使用http.get
发起GET请求。如果请求成功(状态码为200),则解析并返回响应体数据;如果请求失败(状态码非200),则抛出异常。 - 在
main
函数中演示了如何调用封装的getRequest
函数,并处理可能出现的异常。