如何在 Flutter Web 应用程序中保存和下载文本文件 [英] How to save and download text file in Flutter web application

查看:58
本文介绍了如何在 Flutter Web 应用程序中保存和下载文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.
}

谁能帮我实现这个目标

推荐答案

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

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

代码片段:

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);

这里DartPad演示.

这篇关于如何在 Flutter Web 应用程序中保存和下载文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆