Futures and async-await

  • Futures and async-await

Future and Async-await

The future and async/await are the ones that are used in Asynchronous programming to deal with the execution of program to not wait util one function finishes to move forward.

Async/Await In Asynchronous programming in Dart

A async/await keyword make asynchronous programming code easier.an async function returns a Future and await pauses the execution of the function until the future completes. Example

import "dart:io"
void main()async{
    String data = await fetchUserData();
}
Future<String> fetchUserData() async{
  await Future.delayed(Duration(seconds: 2));
  return 'User: Andy';
}

Future

A Future represents a potential value or error that will be available at some time in the future.The Future as “means getting a value sometime in future.” Several of Dart’s bult-in-classes return a Future when an asynchronous method is called. You can use ’then, ‘catchError’, ‘whenComplete’ to handle a ‘future’.

import "dart:io"
void main(){
  File file = new File( Directory.current.path+"\\data\\contact.txt"); 
   Future<String> f = file.readAsString();  
  
   // returns a futrue, this is Async method 
   f.then((data)=>print(data));  
    print("End of main");
}