Why do Learn Async Programming?
Asynchronous operations make your program non-blocking. You call some async operations and your code it not waiting to complete the operation. Here are some common asynchronous operations:
- Fetching data over a network.
- Writing data to a database.
- Reading data from a file.
Async codes provides the result in form of Future or Stream.
Future example code
Future.delayed(
const Duration(seconds: 2),
() => 'Result after 2 sec',
);
Future has 2 States
- UnCompleted
- Completed - Completed can be with value or Completed with error.
Future with Completed Successfully completed state.
Future<String> fetchUserInfo() {
return Future.delayed(const Duration(seconds: 5), () => "Amit Srivastava");
}
Future with Completed Error.
Future<void> fetchUserInfo() {
return Future.delayed(const Duration(seconds: 5),
() => throw Exception('No User Found...'));
}
The await
means Async Wait, It means function executes asynchronously and, when it is done, continue on to the next line of code.
Note: you can't use await without async.
Generally it is recommened during login , register, payments where you need to wait till async code execute and then move to the next line.
Future<String> login(){
return Future.delayed(const Duration(seconds: 5), ()=>"Login Done ");
}
void main() async{
var r = await login();
print(r);
}
Note : For Error Handling during await use try catch.
That's all Folks catch you in next tutorial.