本文介绍了Flutter:如何在电话屏幕上显示资产中的短文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经整理了有关在Flutter中读写文件的所有答案。他们都没有回答如何在手机屏幕上显示文本文件的问题。

I have ckecked all the answers about reading and writing file in Flutter. None of them answers the question of how to display a text file on the screen of the phone.

我要做的就是拥有要调用的函数/方法作为输入的文件名,它将在我导航到的电话的新屏幕上在我的资产目录中显示一个简短的文本文件。该文件已正确放置在资产中,并在yaml文件中提及。我已经看到了使用的建议:

All I want to do is to have a function/method to call with the filename as input, which will display a short text file from my assets directory on a new screen on the phone that I have navigated to. The file is correctly placed in assets and mentioned in the yaml file. I have seen the suggestion to use:

Future loadAsset() async {
return await rootBundle.loadString('assets/my_text.txt');
}

但我不知道如何使用它以及使用什么代码在屏幕上显示文件。

but I don't know how to use it and what code to use to display a file on the screen.

推荐答案

我想您知道如何在屏幕上显示文本,所以我只是尝试解释一下我通常如何读取文件。

I suppose that you know how to display a Text on the Screen, so I will just try to explain how I normally read files.

首先,您必须导入:

import 'package:path_provider/path_provider.dart';
import 'dart:io';

然后,在您的班级中,您可以使用以下命令:

and then, in your class, you can use this:

Future<void> readMyFile() async {
  Directory directory = await getApplicationDocumentsDirectory();
  var _localFilePath = (directory.path + "yourfile.txt");

     if (FileSystemEntity.typeSync(_localFilePath) == FileSystemEntityType.file) {
       final myFile = await _localFile(_localFilePath);
       List<String> linesAsList = await myFile.readAsLinesSync();

    for (var i = 0; i < linesAsList.length; i++) {
      //print("Line No: " + i.toString() + "\n");
      print(linesAsList[i]);
    }
  }
}

Future<File> _localFile(String myPath) async {
  return File(myPath);
}

最后,文件内容在linesAsList中作为列表行。

At the end, the content of your file is in linesAsList as a list of lines.

这篇关于Flutter:如何在电话屏幕上显示资产中的短文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 14:02