首页 > 解决方案 > Flutter 创建文件并写入其内容

问题描述

我正在开发一个从服务器收集文本内容的应用程序,下一步我试图将它们保存到单独的文件中,以便保存在应用程序存储中。存储是一个名为“存储”的文件夹。在存储内部,有一个“ fileList.txt ”文件,其中包含文件列表。

pubspec.yaml我在资产中声明了这个文件夹,如下所示:

 assets:
- storage/

我可以使用以下函数阅读它:

Future<String> readFileContent() async {
    String response;
    response =
        await rootBundle.loadString('storage/fileList.txt');
    return response;
  }

为了保存文件,我使用了使用“ path_provider ”包的在线示例。但是,当我尝试使用以下函数保存下载的文件之一时,例如“ file4.dat ”,我遇到以下错误。我该如何解决这个问题?

  saveFileLocally() async {
    await _writeFile();
  }
  
  Future<Null> _writeFile() async {
    await (await _getLocalFile()).writeAsString(vars.fileContents);
  }

  Future<File> _getLocalFile() async {
    // get the path to the document directory.
    String dir = (await PathProvider.getApplicationSupportDirectory()).path;
    print('DIR :::: ' + dir);
    return new File(
        '$dir/storage/files/file' + vars.newFileID.toString() + '.dat');
  }

错误是:

Unhandled Exception: FileSystemException: Cannot open file, 
path = '/data/user/0/com.example.ferenova_flutter_app/files/storage/file4.dat'
(OS Error: No such file or directory, errno = 2)

谢谢大家,保重!!!:)

标签: flutterpathprovidercreatefile

解决方案


在查看path_provider示例时,我遇到了这个重要的细节:

Directory directory = Platform.isAndroid
        ? await getExternalStorageDirectory() //FOR ANDROID
        : await getApplicationSupportDirectory(); //FOR iOS

这解决了我的问题。我不再使用默认rootBundle资产来处理任何外部文件。


推荐阅读