Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Future String in flutter [closed]

So I have a function that returns a value that is of future. When this function executes I want to extract the string from the future. How should I do this?

Future<String> coverImage(id, space) {
  String link = 'https://cdn.contentful.com/spaces/$space/assets/$id?access_token=1d4932ce2b24458e85ded26532bb81184e0d79c1a16c5713ec3ad391c2e8f5b3';
  return http.get(link).then((response) => decodeToImage(decodeJson(response.body)));   
}

this function return Future<String>, i want to extract to string when i am using with image widget

like image 382
Shreya Avatar asked Aug 16 '17 05:08

Shreya


People also ask

How do you handle Future error in Flutter?

That error is handled by catchError() . If myFunc() 's Future completes with an error, then() 's Future completes with that error. The error is also handled by catchError() . Regardless of whether the error originated within myFunc() or within then() , catchError() successfully handles it.

What is then () in Flutter?

What is Async/Await/then In Dart/Flutter? await is to interrupt the process flow until the async method completes. then however does not interrupt the process flow. This means that the next instructions will be executed. But it allows you to execute the code when the asynchronous method completes.

What is Future value in Flutter?

Future<T>. value constructor Null safety Creates a future completed with value . If value is a future, the created future waits for the value future to complete, and then completes with the same result. Since a value future can complete with an error, so can the future created by Future.


1 Answers

Future someMethod() async {
  String s = await someFuncThatReturnsFuture();
}

or

someMethod() {
  someFuncTahtReturnsFuture().then((s) {
    print(s);
  });
}

There is no way to go from async (Future) to sync execution. async/await is only syntactic sugar to make the code look more like sync code, but as you see in my first example, someMethod will return a Future and if you want to use the string s on the call site, you have to use async/await or then() there.

like image 58
Günter Zöchbauer Avatar answered Sep 30 '22 12:09

Günter Zöchbauer