1

I have a ".txt" file called "bio.txt" inside the Document folder of my application. I want to read its content and store it inside a String variable. My problem is that the "reading action" is a "Future" function and I have some troubles to save its value in a "String".

I read the file with :

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

Future<File> _localFile(String name) async {
  final path = await _localPath;
  return File('$path/$name');
}

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

    // Read the file.
    return await file.readAsString();
  } catch (e) {
    // If encountering an error, return 0.
    return "Can't read";
  }
}

And I would like to save it with :

String _bio = _read("bio.txt").then((value) => String);

Do you know why this solution isn't working? Any suggestion?

1
  • You can read more about async/futures here at dart.dev/codelabs/async-await. Commented May 28, 2020 at 15:25

3 Answers 3

2

Because the then of Futures won't return a value, it should be like this,

var _bio;

_read("bio.txt").then((value) {
  _bio = value;
});

or by making the context _bio is in to an asynchronous one,

var _bio = await _read("bio.txt");
Sign up to request clarification or add additional context in comments.

3 Comments

I Don't want to store values inside a "var" but inside a "String".
@MichealRoss Then use String _bio in the first version, or just use the second version (in which case type inference will make _bio a String).
@MichealRoss I opt-out the type for _bio because the read function already has a return type that makes _bio a String. Dart, not like Java, only use types for checking and types are not passed down to compilation. Using fewer types without losing the type safety is better in Dart.
1

You can either use a then block or use the async/await

_read ('file.txt').then((value){
bio = value;
 });

Or:

bio = await _read ('file.txt');

Comments

0

This is my solution :

String _myRead( String filename){
 var _bio;

 _read("bio.txt").then((String) {
   _bio = String;
 });
 return _bio;
}
String _bio=_myRead("bio.txt");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.