Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To read and Write File in Flutter Web

I am working on flutter-web, I would like to do file operations(read and write) in flutter-web. For Android and IOS, I was using path_provider dependency. But in flutter-web it is not supported.

Can anyone help me with this. An example would be more helpful.

Thank you

like image 263
Yogesh Avatar asked Jul 24 '19 12:07

Yogesh


People also ask

How do I write a file in Flutter web?

You can select a file through the system's file picker and read it afterward. An easy option to "write" a file is to send the user an auto-download. Save this answer. Show activity on this post.


1 Answers

The accepted answer is not completely right. Yes, dart:io is not available on the web, but it is still possible to read files. You can select a file through the system's file picker and read it afterward. An easy option to "write" a file is to send the user an auto-download.

Read:
Use this library to select a file: pub.dev/packages/file_picker (Web migration guide)

import 'dart:html' as webFile;
import 'package:file_picker_web/file_picker_web.dart' as webPicker;

if (kIsWeb) {
   final webFile.File file = await webPicker.FilePicker.getFile(
      allowedExtensions: ['pd'],
      type: FileType.custom,
   );
  
   final reader = webFile.FileReader();
   reader.readAsText(file);

   await reader.onLoad.first;

   String data = reader.result;
}

Write (a.k.a download):

import 'dart:html' as webFile;

if (kIsWeb) {
   var blob = webFile.Blob(["data"], 'text/plain', 'native');

   var anchorElement = webFile.AnchorElement(
      href: webFile.Url.createObjectUrlFromBlob(blob).toString(),
   )..setAttribute("download", "data.txt")..click();
}
like image 147
David Peters Avatar answered Sep 19 '22 17:09

David Peters