What are Async and Await?
Asynchronous programming allows your app to perform time‑consuming tasks (like network requests, file I/O, or database queries) without freezing the user interface. In Flutter, you can use async and await to write asynchronous code that looks like synchronous code, making it easier to read and maintain. The async keyword marks a function as asynchronous, and await is used to wait for a Future to complete without blocking the main thread.
Basic Syntax
The async function returns a Future automatically. Inside, you can use await to pause execution until the Future completes, but the thread is free to handle other events. When the Future completes, the function resumes with the result.
Using Async/Await in Flutter Widgets
In Flutter, you often need to perform async work in response to user actions or when the widget initializes. The typical places are:
initState: For loading initial data (e.g., fetch user profile).
onPressedcallbacks: For actions like submitting a form or fetching more data.
FutureBuilder: To handle async state reactively.
Example: Loading Data in initState
Note: initState cannot be marked async because it must return void. Instead, you call an async function and use setState to update the UI when the future completes.
Handling Errors
Use try/catch to handle errors in async functions. This is essential for user‑friendly error messages.
Async/Await with FutureBuilder
FutureBuilder is often a cleaner way to handle async data without manual state management. You provide a future and a builder that receives a snapshot. The builder is called when the future completes, with snapshot.hasData, snapshot.hasError, and snapshot.data available.
Common Pitfalls and Best Practices
- Don't forget
await: Calling an async function withoutawaitwill start it but not wait for completion. This can lead to race conditions.
- Don't forget
- Avoid
asyncin build methods: Thebuildmethod is called often; starting an async operation inside it will restart on every rebuild. UseinitStateorFutureBuilder.
- Avoid
- Check
mountedbefore callingsetState: After an async operation, the widget might have been disposed. Useif (mounted)to avoid memory leaks.
- Check
- Cancel ongoing operations if needed: If the widget is disposed while an async operation is running, use a flag to ignore the result.
Complete Example: User Profile Loader
Key Takeaways
asyncmarks a function that returns aFuture.
awaitpauses the function until theFuturecompletes, without blocking the UI.
- Use
try/catchto handle errors in async code.
- Use
- In Flutter, perform async work in
initState,onPressed, orFutureBuilder.
- In Flutter, perform async work in
- Always check
mountedbefore callingsetStateafter an async operation.
- Always check
- Prefer
FutureBuilderfor reactive async UI.
- Prefer