tezvyn:

Dart's async/await: Non-Blocking Code That Reads Synchronously

AI-drafted, machine-checkedSource: dart.devintermediate

Dart's `async`/`await` makes non-blocking code read like a simple script. Use it for network requests or file I/O to keep your UI from freezing. The biggest footgun is calling an async function but forgetting to `await` its `Future` result.

WHY IT EXISTS To prevent an application from freezing while waiting for long operations like network calls or database queries. Without asynchronous patterns, a time-consuming task would halt the entire program, making UIs unresponsive and creating a poor user experience.

THE MENTAL MODEL Think of async/await as a "pause and resume" button for your functions. An async function can be paused with await when it encounters a time-consuming task (a Future). While paused, Dart's event loop can do other work, like rendering the UI. Once the task is done, the function resumes exactly where it left off with the result.

HOW IT WORKS A function marked with the async keyword automatically returns a Future. Inside that function, you can use the await keyword before calling another function that returns a Future. This tells Dart to suspend the execution of the current function until that Future completes. The code looks synchronous, like var data = await fetchData();, but it doesn't block the program.

WHEN TO USE IT Use async and await whenever you call a function that returns a Future and you need its result before the function can continue. This is the standard pattern for handling network requests, file I/O, and database queries in Dart and Flutter. Any function that uses await must be marked as async.

WHEN NOT TO USE IT Avoid await if you want to fire off an operation and don't need to wait for its result. If you need to run multiple asynchronous operations concurrently and wait for them all to finish, using Future.wait() is more efficient than awaiting each one sequentially, as sequential awaits would execute one after the other, not in parallel.

ONE CANONICAL EXAMPLE To fetch user data, you'd write final user = await fetchUserData();. This line, inside an async function, pauses execution. It waits for the fetchUserData() Future to complete its network request and return a user object. Only then does it assign the object to the user variable and proceed. If you forgot await, user would be a Future<User>, not the User object itself, leading to errors downstream.

Read the original → dart.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.