Flutter Web Application 保存json文件

883 阅读1分钟

Flutter Web Application 保存json文件

在flutter web 网站开发中遇到保存页面json的超链接问题(下载json),浏览器默认情况下会打开新的html页面加载json问题。 解决方案:

//提前引入所需的 package
import 'dart:html' as html;

// 下载文件 url=下载文件地址

  _launchURL(String url) async {

    //拆分url 获取文件名
    List elements = url.split("/");
    final fileName = elements[elements.length-1];
    //下载文件
    await NetUtils.get(url,params: {}).then((value){

      var response = jsonDecode(value);
      final blob = html.Blob([response]);
      final urlPath = html.Url.createObjectUrlFromBlob(blob);
      final anchor = html.document.createElement('a') as html.AnchorElement
        ..href = urlPath
        ..style.display = 'none'
        ..download = fileName;
      html.document.body.children.add(anchor);
      // download
      anchor.click();
     // cleanup
      html.document.body.children.remove(anchor);
      html.Url.revokeObjectUrl(url);

    });
  }

只是记录问题