2

I am using Dart VM version: 1.24.3 (Wed Dec 13 23:26:59 2017) on "macos_x64" WITH Flutter 0.2.8 • channel beta Framework • revision b397406561 (13 days ago) Engine • revision c903c217a1 Tools • Dart 2.0.0-dev.43.0.flutter-52afcba357

ReadAsStringSync is giving me an empty string as an output rather than the required file content, my code is

var appl = new File('a.txt').readAsStringSync();
print(appl);

also i need help with the readAsString method as it returns a Future<String>, i want to know that is there any method or way to convert it into String

Sahil Yadav
  • 88
  • 1
  • 9
  • The Dart VM version is irrelevant when you are working with Flutter. Only the versions provided by `flutter doctor` or `flutter version` are relevant. – Günter Zöchbauer Apr 16 '18 at 05:50

1 Answers1

2
Future<String> readFile(String path) {
  return new File(path).readAsString();
}

void foo() async {
  var result = await readFile(path);
  print(result);
}

or

String readFile(String path) async {
  var result = await new File(path).readAsString();
  print(result);
  return result;
}
lrn
  • 64,680
  • 7
  • 105
  • 121
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • I am trying to print the value of the returned string someplace else and it gives me **Instance of 'Future' ** as output rather than the string – Sahil Yadav Apr 17 '18 at 11:16
  • With "somplace else" you probable mean where there is no `async` in the method signature and without `await`. That won't work. If you can provide concrete code I might be able to make concrete suggestions. – Günter Zöchbauer Apr 17 '18 at 11:21
  • `var a; // defined globally ie outside any class and method`. and then i call `void foo() async{ a = await readFile('/Users/rajatyadav97/desktop/flutter/assignment_teams/lib/a.txt');}` and print it in `main()` it gives me null as output ps. sorry i am new to dart and stack – Sahil Yadav Apr 17 '18 at 11:30
  • The `print(...)` in `main()` is probably executed before `a = await readFile ...` was able to assign the value. I think you should read about async https://www.dartlang.org/tutorials/language/futures, https://www.dartlang.org/articles/language/await-async – Günter Zöchbauer Apr 17 '18 at 11:38