如何在 Flutter Web 应用程序中保存和下载文本文件

Chi*_*nnu 14 dart flutter flutter-web

我是 Flutter 的新手,正在使用 Flutter Web 应用程序,我的要求是创建和下载文本文件。像下面。

void getData() {
    List<int> bytes = utf8.encode('this is the text file');
    print(bytes); // Need to download this with txt file.
}
Run Code Online (Sandbox Code Playgroud)

谁能帮我实现这一目标

Spa*_*atz 36

此方法基于对HTML文档的操作。应该导入一些额外的包:

import 'dart:convert';
import 'dart:html' as html; // or package:universal_html/prefer_universal/html.dart
Run Code Online (Sandbox Code Playgroud)

代码片段:

final text = 'this is the text file';

// prepare
final bytes = utf8.encode(text);
final blob = html.Blob([bytes]);
final url = html.Url.createObjectUrlFromBlob(blob);
final anchor = html.document.createElement('a') as html.AnchorElement
  ..href = url
  ..style.display = 'none'
  ..download = 'some_name.txt';
html.document.body.children.add(anchor);

// download
anchor.click();

// cleanup
html.document.body.children.remove(anchor);
html.Url.revokeObjectUrl(url);

Run Code Online (Sandbox Code Playgroud)

DartPad演示。

  • DartPad 下载按钮未下载任何文件? (2认同)

Gre*_*rad 17

如果您只想保存文本文件,则此方法比处理所有这些转换更直接:

import 'dart:convert' show utf8;

// ignore: avoid_web_libraries_in_flutter
import 'dart:html' show AnchorElement;

void saveTextFile(String text, String filename) {
  AnchorElement()
    ..href = '${Uri.dataFromString(text, mimeType: 'text/plain', encoding: utf8)}'
    ..download = filename
    ..style.display = 'none'
    ..click();
}
Run Code Online (Sandbox Code Playgroud)

您可以根据需要更改 mimeType 和编码。例如,我必须在最近的项目中生成 CSV 文件,所以我使用了mimeType: 'text/csv'.


Ole*_*ama 13

有另一种方法来做到这一点,通过名为FileSaver 的流行 JS 库

首先,更新您的ProjectFolder/web/index.html文件以包含库并webSaveAs像这样定义函数:

...

<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js"> 
</script>

<script>
function webSaveAs(blob, name) {
  saveAs(blob, name);
}
</script>

<script src="main.dart.js" type="application/javascript"></script>

...
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样从 Dart 代码调用这个函数:

import 'dart:js' as js;
import 'dart:html' as html;

...

js.context.callMethod("webSaveAs", [html.Blob([bytes], "test.txt"])
Run Code Online (Sandbox Code Playgroud)