Can you convert a Future<String> to a String? Flutter/dart

5,759

Solution 1

You just have to await for the value:

string = await futureString;

Since value is Future<String>, await keyword will wait until the task finish and return the value without moving to the next statement.

Note that to use await you have to make your method asyncronous yourMethod() async {}

Or use then callback:

futureString.then((value) {
  string = value;
});

Both are doing the same thing but when you use callback you dont need to make your method asynchronous but the asynchronous will improve readability (use one depend on scenario).

Solution 2

First you need to learn about Asynchronous programming in Dart language.

Here is an example to help you understand how Future works in Dart a bit.

void main() async {
  Future<String> futureString = Future.value('Data from DB');
  
  print(futureString); // output: Instance of '_Future<String>'
  print(await futureString); // output: Data from DB
  
  if (await futureString == null) {
    print('No data');
  }
}
Share:
5,759
Bram van de Munt
Author by

Bram van de Munt

Updated on December 18, 2022

Comments

  • Bram van de Munt
    Bram van de Munt over 1 year

    Can you convert a Future<String> to a String? Every time I start my application, it should get data from the database, store it in a .csv file, read the .csv file and update some string variables. I want my application to run offline.

    I'm looking for a solution like this:

    String string;
    Future<String> = futureString;
    
    if (futureString == null) {
      string = '{standard value}'; 
    } else {
      string = futureString;
    }
    

    I hope you guys get the picture and can help me out! Thanks!