5

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!

3 Answers 3

4

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).

Sign up to request clarification or add additional context in comments.

Comments

3

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');
  }
}

Comments

0

Had The same problem and fixed it like this:

String string;
Future<String> futureString;
string = futureString.get();

1 Comment

This answer is incorrect

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.