Search code examples
flutterofflineflutter-inappwebview

In flutter app, read file system located in the application document directory froma web view widget (inappwebview)


we are working on flutter app to support an offline functionality. This requires to store files (pdfs, binary data, etc). We choose the application document directory for this. Then we also need to pass local paths to an API command.

After creating our http server using inappwebview package and reading our file stored in app doc directory, flutter is reading the path from the assets folder (it always add the extension "assets/" to the input path).

    return InAppWebView(
      initialSettings: InAppWebViewSettings(
          webViewAssetLoader: WebViewAssetLoader(pathHandlers: [
            // InternalStoragePathHandler(path: "", directory: pathdir)
            // AssetsPathHandler(
            //     path: "/data/user/0/com.example.minisitewalkapp/app_flutter/")
          ]),
          allowFileAccess: true), //doesnt solve the issue!!
      onConsoleMessage: (controller, consoleMessage) {
        print(consoleMessage.message);
      },
      initialUrlRequest: URLRequest(
          url: WebUri.uri(
              Uri.parse("http://localhost:8080/assets/wwwroot/index.html"))),
      onWebViewCreated: (controller) {
        // controller.loadUrl(
        //     urlRequest: URLRequest(
        //         url: Uri.parse(
        //             "file://data/user/0/com.example.minisitewalkapp/app_flutter/Floor Plan/Unit Floor Plan1.pdf")));
      },
    );

Is there a workaround or a way officially supported to reference files from the app document directory?

regards, Miguel G

We even tried to play around with the new InAppWebViewSettings option but didn't succedd to get rid of the lecture from the assets folder:

initialSettings: InAppWebViewSettings(
          webViewAssetLoader: WebViewAssetLoader(pathHandlers: [
            // InternalStoragePathHandler(path: "", directory: pathdir)
            // AssetsPathHandler(
            //     path: "/data/user/0/com.example.minisitewalkapp/app_flutter/")
          ]),
          allowFileAccess: true),

Solution

  • Turns out that a workaround for android is to implement a customPathHandler. Checkout this link: https://inappwebview.dev/docs/webview/webview-asset-loader We can intercept flutter assets requests and instead returns bytes coming from app doc directory.

    For ios, it requires to setup a url scheme and implement the onLoadResourceWithCustomScheme command