如何解决飞镖的未来?

Mic*_*oss 3 dart flutter

我需要在 Flutter 上读写文件。

写有效,但不读,或者我认为不是,因为终端输出是flutter: Instance of 'Future<String>'.

这是什么意思?

这是代码:

Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}

Future<File> get _localFile async {
final path = await _localPath;
return File('$path/hello.txt');
}

Future<File> writeHello() async {
final file = await _localFile;

// Write the file.
return file.writeAsString('HelloWorld');
}

Future<String> readHello() async {
try {
final file = await _localFile;

// Read the file.
return await file.readAsString();

} catch (e) {
// If encountering an error, return 0.
return "Can't read";
  }
}
.
.
.
writeHello();
print(readHello());
Run Code Online (Sandbox Code Playgroud)

Yud*_*ngh 7

Future< String > 是 Future 类型,因此您需要解析未来,您可以await在打印之前或用于.then()解析未来。

使用等待

String data = await readHello();
print(data);
Run Code Online (Sandbox Code Playgroud)

使用 .then()

readHello().then((data){ //resolve the future and then print data
  print(data); 
});
Run Code Online (Sandbox Code Playgroud)

注意:不需要在第 2 行添加额外的“await”,因为您已经在第 1 行等待:

Future<String> readHello() async {
  try {
    final file = await _localFile; //Line 1
    // Read the file.
    return await file.readAsString(); //Line 2
  } catch (e) {
    // If encountering an error, return 0.
    return "Can't read";
  }
}
Run Code Online (Sandbox Code Playgroud)