How to save and download text file in Flutter web application

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.

Leave a Comment