flutterflutter-web

how to load local file in InAppWebView in flutter?


I want to load files from internal storage in In App WebView in flutter so that I can load that file in WebView.


Solution

  • Yes you can do that. Here are the steps:

    See the example here, see how it uses HTML strings such as kNavigationExamplePage: https://pub.dev/packages/webview_flutter/example

    const String kNavigationExamplePage = '''
    <!DOCTYPE html><html>
    <head><title>Navigation Delegate Example</title></head>
    <body>
    <p>
    The navigation delegate is set to block navigation to the youtube website.
    </p>
    <ul>
    <ul><a href="https://www.youtube.com/">https://www.youtube.com/</a></ul>
    <ul><a href="https://www.google.com/">https://www.google.com/</a></ul>
    </ul>
    </body>
    </html>
    ''';
    
      Future<void> _onNavigationDelegateExample(
          WebViewController controller, BuildContext context) async {
        final String contentBase64 =
            base64Encode(const Utf8Encoder().convert(kNavigationExamplePage));
        await controller.loadUrl('data:text/html;base64,$contentBase64');
      }
    

    What you need to do is to read this string from a File instead. This answer provides detailed steps on how to do that. Instead of a text file, you will read an HTML file. Later you will use it instead of the kNavigationExamplePage string.

    Flutter - Read text file from assets

    Edit: If you are using flutter_inappwebview, it seems it even has a function that uses your asset files directly: https://pub.dev/documentation/flutter_inappwebview/latest/flutter_inappwebview/InAppWebViewController/loadFile.html