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

3

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!

Aeolis answered 27/2, 2020 at 17:16 Comment(0)
P
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).

Projectile answered 27/2, 2020 at 17:20 Comment(0)
P
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');
  }
}
Photocathode answered 27/2, 2020 at 17:32 Comment(0)
P
0

Had The same problem and fixed it like this:

String string;
Future<String> futureString;
string = futureString.get();
Purpure answered 29/9 at 5:29 Comment(1)
This answer is incorrectMaturate

© 2022 - 2024 — McMap. All rights reserved.