Flutter WEB download option Flutter WEB download option dart dart

Flutter WEB download option


Simple Code for redirecting to download URL

import 'dart:html' as html;void downloadFile(String url){   html.AnchorElement anchorElement =  new html.AnchorElement(href: url);   anchorElement.download = url;   anchorElement.click();}


One way to trigger download is the adapt a common pattern used in "native" javascript, create an anchor element with the download attribute and trigger a click.

import 'dart:convert';import 'dart:html';main() {  File file = // generated somewhere  final rawData = file.readAsBytesSync();  final content = base64Encode(rawData);  final anchor = AnchorElement(      href: "data:application/octet-stream;charset=utf-16le;base64,$content")    ..setAttribute("download", "file.txt")    ..click();}


you can use package url_launcher with url_launcher_web

then you can do:

launch("data:application/octet-stream;base64,${base64Encode(yourFileBytes)}")

EDIT:you don't need a plugin if you do this

download.dart:

import 'dart:convert';// ignore: avoid_web_libraries_in_flutterimport 'dart:html';void download(  List<int> bytes, {  String downloadName,}) {  // Encode our file in base64  final _base64 = base64Encode(bytes);  // Create the link with the file  final anchor =      AnchorElement(href: 'data:application/octet-stream;base64,$_base64')        ..target = 'blank';  // add the name  if (downloadName != null) {    anchor.download = downloadName;  }  // trigger download  document.body.append(anchor);  anchor.click();  anchor.remove();  return;}

empty_download.dart:

void download(  List<int> bytes, {  String downloadName,}) {  print('I do nothing');}

import and use:

import 'empty_download.dart'if (dart.library.html) 'download.dart';void main () {  download('I am a test file'.codeUnits, // takes bytes      downloadName: 'test.txt');}