Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One way to retrieve files from a Flutter webview is to use the JavascriptChannel class. This class allows you to communicate between the Flutter app and the webview using JavaScript. Here's an example of how to retrieve a file from a webview:

  1. Create a WebView widget and add a JavascriptChannel:
WebView(
  initialUrl: 'https://www.example.com',
  javascriptMode: JavascriptMode.unrestricted,
  javascriptChannels: Set.from([
    JavascriptChannel(
      name: 'FileChannel',
      onMessageReceived: (JavascriptMessage message) {
        retrieveFile(message.message);
      },
    ),
  ]),
)
  1. In the webview, create a function that sends the file data to the Flutter app:
function readFile() {
  const fileInput = document.createElement('input');
  fileInput.setAttribute('type', 'file');
  fileInput.click();

  fileInput.addEventListener('change', () => {
    const file = fileInput.files[0];
    const reader = new FileReader();
    reader.readAsDataURL(file);

    reader.onload = () => {
      const fileData = reader.result;
      window.FileChannel.postMessage(fileData);
    };
  });
}

// Call the function to retrieve the file
readFile();
  1. In the Flutter app, create a function that retrieves the file data from the message:
void retrieveFile(String message) {
  final fileData = message.split(',').last;
  // Do something with the file data
}

Note that this example retrieves the file as a data URL. If you need to retrieve the file itself instead of the data URL, you can modify the readFile function to read the file with fetch and send the file data as a binary array instead of a data URL.