Search code examples
javascriptflutterflutter-web

Flutter web Save as File


In flutter web, I created app.js file and used that in the flutter project.
When I release the project and publish it in the IIS javascript function not work.
It's working when I run the project debug or flutter run -d chrome --release.
https://developer.mozilla.org/en-US/docs/Web/API/window/showSaveFilePicker

index.html

<!DOCTYPE html>
<html>
<head>
 ...
 ...
<script src="app.js" defer></script>

<script>
// The value below is injected by flutter build, do not touch.
var serviceWorkerVersion = null;
</script>
<!-- This script adds the flutter initialization JS code -->
<script src="flutter.js" defer></script>
</head>
<body>
...
...
</body>
</html>

app.js

async function saveFile(blob, fileName) {
const opts = {
    suggestedName: fileName,
    types: [{
        description: 'Text file',
        accept: { 'text/plain': ['.txt'] },
    }],
};

// create a new handle
const newHandle = await window.showSaveFilePicker(opts);

// create a FileSystemWritableFileStream to write to
const writableStream = await newHandle.createWritable();

// write our file
await writableStream.write(blob);

// close the file and write the contents to disk.
await writableStream.close();
}

My Dart Function file_saver.dart

class FileSaver {
 Future saveAs2(List<String> finalLines, String fileName) async {
   await js.context.callMethod(
     'saveFile',
      [
        html.Blob(
        finalLines,
        'text/plain',
        ),
      fileName
      ],
   );
  }
}

Error :

app.js:19 Uncaught (in promise) TypeError: window.showSaveFilePicker is not a function
at saveFile (app.js:19:36)
at lz.la (main.dart.js:41242:19)
at main.dart.js:41902:19
at au6.a (main.dart.js:5401:62)
at au6.$2 (main.dart.js:37029:14)
at Object.H (main.dart.js:5387:10)
at a2R.TA (main.dart.js:41904:10)
at a2R.u9 (main.dart.js:41898:21)
at main.dart.js:42628:13
at au6.a (main.dart.js:5401:62

Solution

  • According to the docs, you must run your app on HTTPS hosts to use this function:

    enter image description here

    Is your hosting supports HTTPS?

    Do you check your URL and are you sure it starts with https?

    browser support showSaveFilePicker And do you run your app on a browser that supports showSaveFilePicker function?