5

The problem is this: I have a .txt file that contains one line of text and I need to read that line into a String variable.

Most of the methods I found return either a Future or Future and I have no idea how to convert these types into Strings. Also, I'm not sure what I'm doing wrong with readAsStringSync because I get a "FileSystemExeption: Cannot open file (OS Error: No such file or directory)", even though I have referenced it in my pubspec.yaml

class LessonPage extends StatelessWidget { LessonPage({this.title, this.appBarColor, this.barTitleColor, this.fileName});
   final String title;
   final Color appBarColor;
   final Color barTitleColor;
   final String fileName;

   @override
   Widget build(BuildContext context) {

      final file = new File(this.fileName);

      return new Scaffold(
        appBar: new AppBar(
           title: new Text(
                     this.title,
                     style: new TextStyle(color: this.barTitleColor)
                  ),
           backgroundColor: this.appBarColor,
        ),
        body: new Center(
           child: new Text(
           file.readAsStringSync(),
           softWrap: true,
        )
    ),
);
2

1 Answer 1

10

Embrace Futures! This use case is exactly what FutureBuilder was made for.

To read assets as strings, you don't need to construct a File. Instead, use DefaultAssetBundle to access asset files. Make sure that the asset file you want to read is declared in pubspec.yaml.

screenshot

    return new Scaffold(
      appBar: new AppBar(
        title: new Text(
          this.title,
          style: new TextStyle(color: this.barTitleColor)
        ),
        backgroundColor: this.appBarColor,
      ),
      body: new Center(
        child: new FutureBuilder(
          future: DefaultAssetBundle.of(context).loadString(fileName),
          builder: (context, snapshot) {
            return new Text(snapshot.data ?? '', softWrap: true);
          }
        ),
      ),
    );

If you're reading a file that isn't an asset (for example, a file you downloaded to a temporary folder) then it's appropriate to use a File. In that case, make sure that the path is correct. Consider using FutureBuilder instead of the synchronous File APIs, for better performance.

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

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.