Introduction to Future
Future provides a way of asynchronous programming, which allows us to execute a task without blocking the current task, and obtain the corresponding result after the task is completed.
Steps to use Future
1. Create a Future object;
2. Specify a callback function for the Future;
3. Pass the Future object to the run() method of the dart:async library;
4. Process the result of the Future in the callback function.
Future usage example
// 创建一个Future对象
Future future = Future(() {
// 执行一些耗时的操作
print('开始执行耗时操作');
// 模拟耗时操作
Future.delayed(Duration(seconds: 4), () {
return '耗时操作完成!';
});
});
// 为Future指定一个回调函数
future.then((data) {
print(data);
});
// 将Future对象传递给dart:async库的run()方法
run(future);
Common usage scenarios
Often used with async
Async is a keyword in Dart used to mark an asynchronous function. The async function returns a Future object, and the await keyword can be used to wait for the execution result of the function.
For example:
Future getData(String url) async {
var response = await http.get(url);
return response.body;
}