2017-05-15 9 views
0

問題は次のとおりです。1行のテキストを含む.txtファイルがあり、その行をString変数に読み込む必要があります。ファイルの内容をFlutterの文字列変数に読み取る

私が見つけたメソッドのほとんどは未来または未来のいずれかを返して、これらのタイプを文字列に変換する方法はわかりません。また、私はpubspec.yamlで参照していますが、 "FileSystemExeption:ファイルを開くことができません(OSエラー:そのようなファイルやディレクトリはありません)"というメッセージが表示されるので、readAsStringSyncで何が間違っているのか分かりません。

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, 
     ) 
    ), 
); 
+0

あなたが探しているものはhttps://flutter.io/assets-and-images/#loading-text-assetsですか? –

+0

pubspec.yamlの内容とファイル名も投稿できますか? –

答えて

3

抱擁Future s!このユースケースはまさにFutureBuilderのためのものです。

アセットを文字列として読み取る場合は、Fileを作成する必要はありません。代わりに、DefaultAssetBundleを使用してアセットファイルにアクセスしてください。読み込みたいアセットファイルが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); 
      } 
     ), 
    ), 
    ); 

ます(たとえば、あなたが一時フォルダにダウンロードしたファイル)の資産ではないファイルを読んでいる場合、それはFileを使用するのが適切です。その場合は、パスが正しいことを確認してください。パフォーマンスを向上させるには、File APIの代わりにFutureBuilderを使用することを検討してください。

関連する問題