面试题答案
一键面试1. 使用 Future
和 async/await
从网络获取数据并处理返回结果的代码示例
假设我们使用 http
库来进行网络请求,首先添加依赖:
dependencies:
http: ^0.13.5
然后编写代码如下:
import 'package:http/http.dart' as http;
import 'dart:convert';
Future<List<dynamic>> fetchData() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
if (response.statusCode == 200) {
return jsonDecode(response.body);
} else {
throw Exception('Failed to load data');
}
}
void main() async {
try {
final data = await fetchData();
print(data);
} catch (e) {
print('Error: $e');
}
}
2. async
函数的返回值类型
async
函数始终返回一个 Future
。如果在 async
函数中没有显式地返回一个 Future
,Dart 会自动将函数的返回值包装在一个 Future
中。例如,如下函数:
asyncFunction() async {
return 42;
}
实际上等价于:
asyncFunction() {
return Future.value(42);
}
3. await
只能在什么函数中使用
await
只能在标记为 async
的函数内部使用。这是因为 await
用于暂停 async
函数的执行,直到其等待的 Future
完成(resolved 或 rejected)。例如:
void normalFunction() {
// 这里不能使用 await,会报错
// await someFuture();
}
Future<void> asyncFunction() async {
await someFuture(); // 这里可以使用 await
}