Returning a String from an async Returning a String from an async dart dart

Returning a String from an async


A function that's annotated with async will always return a Future.

so when you call readUrl(s) you can await its result.

To use await, the caller (here your main function) has to be marked as async. So the end result could look like this:

main() async {  String s = await dummy("http://www.google.com");}Future<String> dummy(String s) async {  String response = await readURL(s);  return (response);}Future<String> readURL(String requestString) async {  String response = await http.read(requestString);  print(response);  return(response);}

The thing to notice here: If you use await in a function, it is now considered as function that returns a Future. So every function you convert to be async will now return a Future.


Here is the Simple Two way to get value from Function with return type Future<Type>

1- First way (best way, as you call this code from any file)

FutureFunctionName.then((val) {      val contains data    });

For example- (I am posting one from real example)

Future<String> getUserAgents() async {  String userAgent;  await FlutterUserAgent.init();  userAgent = FlutterUserAgent.webViewUserAgent;  return userAgent;}
String userAgent;getUserAgents().then((val) {   userAgent = val;});print(userAgent); // you will get output

2- Second way (use a global variable to get data)

String userAgent;Future<void> getUserAgents() async {  await FlutterUserAgent.init();  userAgent = FlutterUserAgent.webViewUserAgent;}print(userAgent);