Where we use await in Flutter?
Flutter Tutorial
Install Flutter in Win/Linux/Mac
Flutter Widgets:
Bottom Navigation Bar in Flutter
Auto Close Keyboard in Flutter
Screen size handling in Flutter
Flutter REST API
Flutter Advance
Wrap vs Builder vs OverBarFlow
Circular progress contain Icon
Flutter State management Comparison
Flutter Database
Flutter Token Expired Handling
Flutter Provider
Flutter GetX
Flutter with Native
Flutter Tips
Interview Questions
In Flutter, we use the await keyword whenever we need to run a specific function or assign a value before proceeding. The await keyword plays a major role in executing a specific function, whether that function is calling an API, or storing data, retrieving data locally( like set or get from sharedPrefernces), etc.
await keyword conjunction with the async keyword to perform asynchronous operations.
Asynchronous operations are crucial for tasks that may take time to complete, such as network requests, file I/O, or database queries.
Network Request where await is required:-
Whenever we use await keyword async keyword also require in function
Future<void> fetchData() async {
//Here we use await
var response = await http.get('https://api.example.com/data');
print('Response: ${response.body}');
}
In this case hello will print after 5 seconds of start print and to implement this functionality we require await with Future.delay
Future<void> delayedOperation() async {
print('Start');
await Future.delayed(Duration(seconds: 5));
//Hello print after 5 seconds
print("Hello");
print('After 2 seconds');
}
In this case try catch is used when exception may be occurs while calling API
Future<void> fetchData() async {
//await with try catch
try {
var response = await http.get('https://api.example.com/data');
print('Response: ${response.body}');
} catch (e) {
print('Error: $e');
}
}
Multiple await within an async function
Future<void> processMultipleSteps() async {
//multiple await
var result1 = await step1();
var result2 = await step2(result1);
print('Results: $result1, $result2');
}
Overall await is very important keyword and it is used in API calling, data storage, handling data flow and many other cases. When storing data through shared preference in flutter, await is always used, to see an example of shared preferences fetchSharePrefData() where await keyword is used, click here