0Pricing
Flutter Mobile Development · 课时

Future 与异步等待

了解 Dart 的 `Future` 类以及 `async`/`await` 关键字,用于执行非阻塞操作和处理延迟结果。

Future 与异步等待 是 CoddyKit 上的免费 Flutter Mobile Development 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Flutter Mobile Development 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Flutter Mobile Development 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

What is Asynchronous Code?

In app development, we often need to perform tasks that take time, like fetching data from the internet or reading a file.

If these tasks block your app's main thread, your UI becomes unresponsive and freezes. This is a bad user experience!

Asynchronous programming allows your app to start a long-running task and continue doing other things (like updating the UI) while waiting for the task to finish.

The Problem with Blocking Code

Imagine a task that takes 3 seconds. If it runs on the main thread, your app will freeze for 3 seconds. Try running this example to see how it blocks:

void main() {
  print("Starting a long task...");
  // Simulate a long-running operation
  var result = _performHeavyCalculation();
  print("Task finished with result: $result");
  print("End of program.");
}

String _performHeavyCalculation() {
  // Simulate delay without async/await
  var startTime = DateTime.now();
  while (DateTime.now().difference(startTime).inSeconds < 3) {
    // Busy-wait, blocking the thread
  }
  return "Calculated Data";
}

Meet the Dart Future

Dart's Future class is your solution for non-blocking operations. A Future represents a potential value or error that will be available at some point in the future.

  • It's like an IOU (I Owe You) for a value.
  • When you call an asynchronous function, it immediately returns a Future object.
  • The actual result will be delivered to the Future when the operation completes.

Think of it as ordering food; you get a receipt (the Future) immediately, but the food (the value) comes later.

Making a Simple Future

You can create a Future that completes after a delay using Future.delayed. It takes a duration and a function to execute when the delay is over.

Run this code to see how the "Data received!" message appears after a short wait, without blocking the "Program continues!" message.

void main() {
  print("Program starts!");

  Future.delayed(Duration(seconds: 2), () {
    print("Data received after 2 seconds!");
  });

  print("Program continues immediately!");
  print("End of main function.");
}

Getting Values with .then()

To actually use the value a Future eventually provides, you attach a callback function using the .then() method.

The code inside .then() will only run once the Future successfully completes and delivers its value. This is how you react to a completed async task.

void main() {
  print("Fetching user data...");

  _fetchUserData().then((userData) {
    print("User data fetched: $userData");
  });

  print("UI can update while data fetches.");
}

Future<String> _fetchUserData() {
  return Future.delayed(Duration(seconds: 2), () => "Alice (ID: 123)");
}

Handling Future Errors

Asynchronous operations can fail (e.g., network issues). To handle errors, you can chain .catchError() after .then(). This callback will execute if the Future completes with an error.

.catchError() receives the error object, allowing you to react gracefully to problems.

void main() {
  print("Attempting to fetch data...");

  _fetchFaultyData().then((data) {
    print("Data received: $data");
  }).catchError((error) {
    print("Error caught: $error");
  });
}

Future<String> _fetchFaultyData() {
  return Future.delayed(Duration(seconds: 2), () {
    throw Exception("Failed to connect to server!");
  });
}

Simplify with async and await

While .then() and .catchError() work, chaining many of them can become hard to read. Dart offers async and await keywords to make asynchronous code look and feel more like synchronous code.

  • async: Marks a function as asynchronous. An async function always returns a Future.
  • await: Can only be used inside an async function. It pauses the execution of the async function until the Future it's waiting on completes.

The rest of the program continues to run while an await is active.

Async/Await in Action

Let's rewrite our user data fetching example using async and await. Notice how much cleaner and more sequential the code looks!

The await keyword makes the code inside main appear to wait, but the main function itself is an async function, so it actually returns a Future and doesn't block the overall program.

void main() async { // main function is now async
  print("Fetching user data with async/await...");

  String userData = await _fetchUserData(); // Await the Future
  print("User data fetched: $userData");

  print("UI can update while data fetches.");
}

Future<String> _fetchUserData() {
  return Future.delayed(Duration(seconds: 2), () => "Bob (ID: 456)");
}

Try-Catch with Async/Await

With async and await, error handling becomes familiar! You can use standard try-catch blocks around await expressions to catch exceptions thrown by Futures.

This makes managing potential failures in asynchronous operations much more intuitive and readable.

void main() async {
  print("Attempting to fetch data with try-catch...");

  try {
    String data = await _fetchFaultyData();
    print("Data received: $data");
  } catch (e) {
    print("Error caught: $e");
  }
  print("Program continues after error handling.");
}

Future<String> _fetchFaultyData() {
  return Future.delayed(Duration(seconds: 2), () {
    throw Exception("Network connection lost!");
  });
}

Check Your Understanding

Consider the following Dart code snippet:

void main() async {
  print("A");
  await Future.delayed(Duration(seconds: 1), () => print("B"));
  print("C");
}

Futures & Async/Await Recap

You've mastered the basics of asynchronous programming in Dart!

  • Future: A placeholder for a value that will be available later.
  • .then()/.catchError(): Methods to handle a Future's success or failure.
  • async: Marks a function that performs asynchronous operations and returns a Future.
  • await: Pauses an async function until a Future completes, making async code read like sync code.
  • try-catch: Used with await for robust error handling.

These tools are crucial for building responsive Flutter apps that interact with external resources. Next, we'll use these concepts to make HTTP requests!

常见问题解答

「Future 与异步等待」课时是免费的吗?

是的 — 「Future 与异步等待」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Flutter Mobile Development 课程的其余内容,请升级到 CoddyKit PRO。 Flutter Mobile Development 课程共包含 4 节课。

「Future 与异步等待」这节课中我会学到什么?

了解 Dart 的 `Future` 类以及 `async`/`await` 关键字,用于执行非阻塞操作和处理延迟结果。 你通过在浏览器中直接运行的动手代码来练习 Flutter Mobile Development,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Flutter Mobile Development 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Flutter Mobile Development 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「Future 与异步等待」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Flutter Mobile Development 课中编写并运行代码吗?

能。每节 Flutter Mobile Development 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. Future 与异步等待
  2. HTTP 请求与 JSON
  3. 异步操作中的错误处理
  4. 流与响应式数据
← 返回 Flutter Mobile Development