问题
I am new to Flutter and working in a flutter web application, My requirement is to create and download a text file. like below.
void getData() {
List<int> bytes = utf8.encode('this is the text file');
print(bytes); // Need to download this with txt file.
}
Can anyone help me to achieve this
回答1:
This method is based on manipulations with an HTML
document.
Some additional packages should be imported:
import 'dart:convert';
import 'dart:html' as html; // or package:universal_html/prefer_universal/html.dart
Code snippet:
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);
Here is DartPad
demo.
回答2:
Got another way to do it, via popular JS library called FileSaver
First, update your ProjectFolder/web/index.html
file to include the library and define the webSaveAs
function like so:
...
<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>
...
Then you can call this function from Dart code like so:
import 'dart:js' as js;
import 'dart:html' as html;
...
js.context.callMethod("webSaveAs", [html.Blob([bytes], "test.txt"])
回答3:
This solution uses FileSaver.js library and it should open the "saveAs" dialog.
I hope it works as intended:
import 'dart:js' as js;
import 'dart:html' as html;
...
final text = 'this is the text file';
final bytes = utf8.encode(text);
final script = html.document.createElement('script') as html.ScriptElement;
script.src = "http://cdn.jsdelivr.net/g/filesaver.js";
html.document.body.nodes.add(script);
// calls the "saveAs" method from the FileSaver.js libray
js.context.callMethod("saveAs", [
html.Blob([bytes]),
"testText.txt", //File Name (optional) defaults to "download"
"text/plain;charset=utf-8" //File Type (optional)
]);
// cleanup
html.document.body.nodes.remove(script);
来源:https://stackoverflow.com/questions/59663377/how-to-save-and-download-text-file-in-flutter-web-application