0Pricing
Flutter Mobile Development · 강의

Future 및 비동기 대기

비차단 작업을 수행하고 지연된 결과를 처리하기 위한 Dart의 `Future` 클래스와 `async`/`await` 키워드를 이해합니다.

Future 및 비동기 대기은(는) CoddyKit의 무료 Flutter Mobile Development 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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 및 비동기 대기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Flutter Mobile Development 강의 전체를 잠금 해제할 수 있습니다. Flutter Mobile Development 강의에는 총 4개의 강의가 포함되어 있습니다.

“Future 및 비동기 대기”에서 뭘 배우나요?

비차단 작업을 수행하고 지연된 결과를 처리하기 위한 Dart의 `Future` 클래스와 `async`/`await` 키워드를 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 Flutter Mobile Development을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Flutter Mobile Development을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Flutter Mobile Development은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“Future 및 비동기 대기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Flutter Mobile Development 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Flutter Mobile Development 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Future 및 비동기 대기
  2. HTTP 요청 및 JSON
  3. 비동기 작업의 오류 처리
  4. Stream과 반응형 데이터
← Flutter Mobile Development(으)로 돌아가기