【问题标题】:Reading the contents of a file into a String variable in Flutter在 Flutter 中将文件内容读入 String 变量
【发布时间】:2017-05-15 20:39:12
【问题描述】:

问题是这样的:我有一个包含一行文本的 .txt 文件,我需要将该行读入一个字符串变量。

我发现的大多数方法都返回 Future 或 Future,我不知道如何将这些类型转换为字符串。另外,我不确定我在 readAsStringSync 上做错了什么,因为我得到一个“FileSystemExeption:无法打开文件(操作系统错误:没有这样的文件或目录)”,即使我在 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,
        )
    ),
);

【问题讨论】:

标签: flutter


【解决方案1】:

拥抱Futures!这个用例正是 FutureBuilder 的用途。

要将资产读取为字符串,您无需构造File。相反,使用DefaultAssetBundle 来访问资产文件。确保您要读取的资产文件在 pubspec.yaml 中声明。

    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);
          }
        ),
      ),
    );

如果您正在读取不是资产的文件(例如,您下载到临时文件夹的文件),那么使用File 是合适的。在这种情况下,请确保路径正确。考虑使用FutureBuilder 而不是同步的File API,以获得更好的性能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    • 2011-03-05
    • 2016-09-26
    • 2012-07-22
    • 1970-01-01
    相关资源
    最近更新 更多