Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Load HTML from assets or local files #27086

Closed
durduman opened this issue Jan 25, 2019 · 29 comments · Fixed by flutter/plugins#4593
Closed

Load HTML from assets or local files #27086

durduman opened this issue Jan 25, 2019 · 29 comments · Fixed by flutter/plugins#4593
Labels
c: new feature Nothing broken; request for a new capability customer: crowd Affects or could affect many people, though not necessarily a specific customer. p: webview The WebView plugin P3 Issues that are less important to the Flutter project package flutter/packages repository. See also p: labels.

Comments

@durduman
Copy link

durduman commented Jan 25, 2019

I am loading a local HTML file into a Widget using flutter_webview package in the following way:

                        FutureBuilder<String>(
                            future: LocalLoader().loadLocal(),
                            builder: (context, snapshot) {
                              if (snapshot.hasData) {
//                                return Text("${snapshot.data}");
                                return WebView(
                                  initialUrl: new Uri.dataFromString(snapshot.data, mimeType: 'text/html').toString(),
                                  javascriptMode: JavascriptMode.unrestricted,
                                );

                              } else if (snapshot.hasError) {
                                return Text("${snapshot.error}");
                              }
                              return CircularProgressIndicator();
                            }
                        )

It loads the HTML just fine but if the tags point to other resources (such as an external CSS file or other local images), they will not be displayed in the webview.

These assets (CSS and the images files) are added to the project at the location specified path from the HTML ( relative local path ) and also the pubspec.


For example one of the HTML files contains this element:
<link rel=stylesheet href=styles/main.css>

When the HTML file loads in the webview, the CSS will not reflect in the style for that page.
If I manually add the CSS to the HTML (using <style> element to define it) it will work just fine.

Any suggestion on how I can make these HTMLS load their local resources? (even it it means changing the package or the way it was implemented)

@zoechi
Copy link
Contributor

zoechi commented Jan 25, 2019

The discussion for an immediate workaround is in #27078

I can imagine that there is a way to make this work in the webview plugin directly to load from an asset file or directory.
So I leave this to the plugin manager to decide.

@zoechi zoechi added c: new feature Nothing broken; request for a new capability plugin p: webview The WebView plugin labels Jan 25, 2019
@zoechi zoechi added this to the Stretch Goals milestone Jan 25, 2019
@zoechi zoechi reopened this Jan 25, 2019
@zoechi
Copy link
Contributor

zoechi commented Jan 25, 2019

I reopen because I think this is a valid feature request and a common one (see fluttercommunity/flutter_webview_plugin#23)

#25162 might be related.

@zoechi zoechi changed the title webview_flutter html + CSS + assets Load HTML from assets or local files Jan 27, 2019
@sageata
Copy link

sageata commented Mar 2, 2019

I think this is a very important new feature.

Soon more and more developers will start using Flutter and they will probably come into the same issues related to the inability to load HTML strings WebViews.

Currently, I am creating a local server and load my webpage from there, if there is another app that uses the same workaround there might be issues resulting from this.

@BRLOKESH
Copy link

BRLOKESH commented Aug 7, 2019

image not load within local html file in webview

@xwysun
Copy link

xwysun commented Aug 9, 2019

unzip the apk package,I found the reason: path is wrong;

For Android:

"assets/test.html" == "file:///android_asset/flutter_assets/assets/test.html"

so,just like this:

WebView(
initialUrl: "file:///android_asset/flutter_assets/assets/test.html",
javascriptMode: JavascriptMode.unrestricted,
)
you can load "assets/test.html".

@ydwan
Copy link

ydwan commented Aug 12, 2019

unzip the apk package,I found the reason: path is wrong;

For Android:

"assets/test.html" == "file:///android_asset/flutter_assets/assets/test.html"

so,just like this:

WebView(
initialUrl: "file:///android_asset/flutter_assets/assets/test.html",
javascriptMode: JavascriptMode.unrestricted,
)
you can load "assets/test.html".

hi,你说的这个方式我试过了,但是直接assets/test.html在ios中还是加载失败。ios设备12.2 和webview_flutter 0.3.10+4

@Justwen
Copy link

Justwen commented Sep 2, 2019

If I try loading assets image in the local html data with Uri.dataFromString, it will prompt "Not allowed to load local resource".
Seems there is not such a way to load asset image now in html now ?

@divan
Copy link

divan commented Sep 3, 2019

I use this patch to my fork to open local files with webview_flutter:

diff --git a/packages/webview_flutter/android/src/main/java/io/flutter/plugins/webviewflutter/FlutterWebView.java b/packages/webview_flutter/android/src/main/java/io/flutter/plugins/webviewflutter/FlutterWebView.java
index a2bed900..83982481 100644
--- a/packages/webview_flutter/android/src/main/java/io/flutter/plugins/webviewflutter/FlutterWebView.java
+++ b/packages/webview_flutter/android/src/main/java/io/flutter/plugins/webviewflutter/FlutterWebView.java
@@ -35,6 +35,14 @@ public class FlutterWebView implements PlatformView, MethodCallHandler {
     platformThreadHandler = new Handler(context.getMainLooper());
     // Allow local storage.
     webView.getSettings().setDomStorageEnabled(true);
+    webView.getSettings().setLoadWithOverviewMode(true);
+    webView.getSettings().setUseWideViewPort(true);
+    webView.getSettings().setJavaScriptEnabled(true);
+    webView.getSettings().setAllowFileAccessFromFileURLs(true);
+    webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
+    webView.getSettings().setBuiltInZoomControls(true);
+    webView.getSettings().setDisplayZoomControls(true);
+    webView.getSettings().setSupportZoom(true);

     methodChannel = new MethodChannel(messenger, "plugins.flutter.io/webview_" + id);
     methodChannel.setMethodCallHandler(this);
diff --git a/packages/webview_flutter/ios/Classes/FlutterWebView.m b/packages/webview_flutter/ios/Classes/FlutterWebView.m
index afc2f992..3b510c0c 100644
--- a/packages/webview_flutter/ios/Classes/FlutterWebView.m
+++ b/packages/webview_flutter/ios/Classes/FlutterWebView.m
@@ -279,7 +279,20 @@ - (bool)loadUrl:(NSString*)url {
 }

 - (bool)loadUrl:(NSString*)url withHeaders:(NSDictionary<NSString*, NSString*>*)headers {
-  NSURL* nsUrl = [NSURL URLWithString:url];
+  NSURL* nsUrl = [NSURL fileURLWithPath:url];
+  if ([url.lowercaseString hasPrefix:@"file://"]) {
+    url = [url substringFromIndex:7]; // length of 'file://'
+
+    NSURL *nsUrl = [NSURL fileURLWithPath:url];
+    NSURL *readAccessToURL = [[nsUrl URLByDeletingLastPathComponent] URLByDeletingLastPathComponent];
+    NSLog(@"\nOpening as file \(nsUrl)");
+
+    [_webView loadFileURL:nsUrl allowingReadAccessToURL:readAccessToURL];
+    return true;
+  }
+
+  NSLog(@"\nOpening as URL \(nsUrl)");
+  nsUrl = [NSURL URLWithString:url];
   if (!nsUrl) {
     return false;
   }

@jazzbpn
Copy link

jazzbpn commented Sep 16, 2019

unzip the apk package,I found the reason: path is wrong;

For Android:

"assets/test.html" == "file:///android_asset/flutter_assets/assets/test.html"

so,just like this:

WebView(
initialUrl: "file:///android_asset/flutter_assets/assets/test.html",
javascriptMode: JavascriptMode.unrestricted,
)
you can load "assets/test.html".

What about iOS? How to load asset image using html in flutter? This only works for android? Elaborated question at stack overflow.

https://stackoverflow.com/questions/57702924/how-to-render-image-using-html-css-using-flutter-to-create-ios-app

@JayM96
Copy link

JayM96 commented Sep 27, 2019

Can anyone please suggest me a way to check whether a given string is file path or network url path?

@Nico04
Copy link

Nico04 commented Sep 27, 2019

Can anyone please suggest me a way to check whether a given string is file path or network url path?

network url will have "https://" or "http://", and local url will have "file://" or starts with "/" (for unix systems, which iOS and Android are, if that is the question ?

@ouyangsuhao
Copy link

ouyangsuhao commented Mar 15, 2020

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
//https://medium.com/flutter-community/loading-local-assets-in-webview-in-flutter-b95aebd6edad
class ExamInstructionsPage extends StatefulWidget {
  @override
  _ExamInstructionsPageState createState() => _ExamInstructionsPageState();
}

class _ExamInstructionsPageState extends State<ExamInstructionsPage> {
  WebViewController _webViewController;
  String filePath = 'assets/files/ExamInstructions.html';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('考试须知')),
        body: WebView(
//          initialUrl: '',
          javascriptMode: JavascriptMode.unrestricted,
          onWebViewCreated: (WebViewController webViewController) {
            _webViewController = webViewController;
            _loadHtmlFromAssets();
          },
          onPageStarted: (url){//Invoked when a page starts loading.
            print('开始加载webview');
            EasyLoading.show(status: 'loading...');
          },
          onPageFinished: (url) {
            print('加载完成webview');
            EasyLoading.dismiss(animation:false);
          },
        )
    );
  }

  _loadHtmlFromAssets() async {
    String fileHtmlContents = await rootBundle.loadString(filePath);
    _webViewController.loadUrl(Uri.dataFromString(fileHtmlContents,
        mimeType: 'text/html', encoding: Encoding.getByName('utf-8'))
        .toString());
  }
}

ExamInstructions.html

The picture below can't be loaded without error

 <div>
    <img src="../images/exam_Instructions.jpg">
      <img src="./home_swiper3.png" alt='图片3加载失败' style="width: 300px; height: 300px;">
  </div>

It loads the HTML just fine but It doesn't load locally images ( fail), the images will not be displayed in the webview.

@asjqkkkk
Copy link

@ouyangsuhao have a try for this pr:
flutter/plugins#2583

@asjqkkkk
Copy link

load asset file or local file

  webview_flutter:
    git:
      url: https://github.com/asjqkkkk/plugins.git
      path: packages/webview_flutter
      ref: webview

Assetfiles

    WebView(
      onWebViewCreated: (WebViewController controller) {
        final url = 'assets/index.html';
        controller.loadAssetHtmlFile(url);
      },
      javascriptMode: JavascriptMode.unrestricted,
    );

Localfiles

    WebView(
      onWebViewCreated: (WebViewController controller) {
        controller.loadLocalHtmlFile(filePath)
      },
      javascriptMode: JavascriptMode.unrestricted,
    );

  Future<void> downloadFile(String url) async {
    Dio dio = Dio();
    String path = (await getApplicationDocumentsDirectory()).path;
    String fileName=url.substring(url.lastIndexOf("/")+1);
    await Dio().download(url, '$path/$fileName',onReceiveProgress: (rec,total){
      progress = ((rec/total) * 100).floor();
      if(progress >= 100){
        filePath= '$path/$fileName';
      }
      setState(() {});
    });
  }

the pr link is there: flutter/plugins#2583

@xiangzhihong
Copy link

I have a problem,about JS call Flutter,like this:
js call Flutter: BiliJsObject.goBackNativeWithJson("{"type": 0}")
in andrid native ,we can use below:
`webView.addJavascriptInterface(new BiliJsObject(), "BiliJsObject");

public class BiliJsObject {

@JavascriptInterface
public void goBackNativeWithJson(String msg) {
    System.out.println("BiliJsObject: "+msg);
}

}
`
but in Flutter ,i use javascriptChannels,faild,

`JavascriptChannel _javascriptChannel(BuildContext context) =>
JavascriptChannel(
name: 'BiliJsObject',
onMessageReceived: (JavascriptMessage message) async {

        });`

@zfc0812
Copy link

zfc0812 commented May 7, 2020

@ouyangsuhao have a try for this pr:
flutter/plugins#2583

Thanks for the PR, but unfortunately Google still haven't merge it after 2 months. How I can access it in my project? What I should add in my pubspec.yaml file?

@asjqkkkk
Copy link

asjqkkkk commented May 7, 2020

@ouyangsuhao have a try for this pr:
flutter/plugins#2583

Thanks for the PR, but unfortunately Google still haven't merge it after 2 months. How I can access it in my project? What I should add in my pubspec.yaml file?

  webview_flutter:
    git:
      url: https://github.com/asjqkkkk/plugins.git
      path: packages/webview_flutter
      ref: webview

you can import it like this

@zfc0812
Copy link

zfc0812 commented May 7, 2020

    WebView(
      onWebViewCreated: (WebViewController controller) {
        final url = 'assets/index.html';
        controller.loadAssetHtmlFile(url);
      },
      javascriptMode: JavascriptMode.unrestricted,
    );

you can use it like this

I do not want to load the html file from assets, I only need the image from assets. _html is a local String and I need to load it as Uri.dataFromString. The problem is how to load the image from assets. Do I need to modify this? <img src="image.jpeg">?

String _html = '<html><body><img src="image.jpeg"></body></html>';
WebView(
          onWebViewCreated: (WebViewController controller) {
            controller.loadUrl(Uri.dataFromString(
                _html,
                mimeType: 'text/html',
                encoding: Encoding.getByName('utf-8')
            ).toString());
          },
)

@asjqkkkk
Copy link

asjqkkkk commented May 7, 2020

String _html = '<html><body><img src="image.jpeg"></body></html>';
WebView(
          onWebViewCreated: (WebViewController controller) {
            controller.loadUrl(Uri.dataFromString(
                _html,
                mimeType: 'text/html',
                encoding: Encoding.getByName('utf-8')
            ).toString());
          },
)

The relative path of the image file is uncertain, so you can't use it like this. Maybe you need find another way to load these htmls

@kf6gpe kf6gpe added the P3 Issues that are less important to the Flutter project label May 29, 2020
@Hixie Hixie removed this from the - milestone Aug 17, 2020
@kakyoism
Copy link

kakyoism commented Sep 8, 2020

I opened #65379. Although somewhat related to this issue, it is more serious than I had thought. Please see below.

Attempt

To work around #65379 and #27086, I thought about merging help_en.html and help_fr.html into a single html file and turn the href's into anchors so that I can bypass the local assets reference issue by jumping within the same html file.

In theory, this would work.

Trouble

However, to my surprise, this didn't work either! This time, instead of going blank, webview gives no response when trying to go to the anchors. The same anchors work fine in an Electron test app and in the browsers.

This time I got an error in Android Studio's console

E/InputMethodManager(28987): b/117267690: Failed to get fallback IMM with expected displayId=259 actual IMM#displayId=0 view=io.flutter.plugins.webviewflutter.InputAwareWebView{b193667 VFEDHVC.. .F...... 0,0-2075,706}
I/chromium(28987): [INFO:CONSOLE(0)] "Not allowed to navigate top frame to data URL: data:text/html;charset=utf-8,%3C!DOCTYPE%20html%3E%0A%3Chtml%20xmlns=%22http://www.w3.org/1999/xhtml%22%20lang=%22%22%20xml:lang=%22%22%3E%0A%3Chead%3E%0A%20%20%3Cmeta%20charset=%22utf-8%22%20/%3E%0A%20%20%3Cmeta%20name=%22generator%22%20content=%22pandoc%22%20/%3E%0A%20%20%3Cmeta%20name=%22viewport%22%20content=%22width=device-width,%20initial-scale=1.0,%20user-scalable=yes%22%20/%3E%0A%20%20%3Ctitle%3E%20%3C/title%3E%0A%20%20%3Cstyle%3E%0A%20%20%20%20code%7Bwhite-space:%20pre-wrap;%7D%0A%20%20%20%20span....E4%BA%8E%3C/h1%3E%0A%3Ch3%20id=%22section%22%3E%3C/h3%3E%0A%3Ch2%20id=%22%E5%8A%A8%E5%90%AC-version-1.0%22%3E%E5%8A%A8%E5%90%AC%20version%201.0%3C/h2%3E%0A%3Cp%3ECopyright%C2%A9%202020%20NExT%20%E5%B7%A5%E4%BD%9C%E5%AE%A4%E7%BE%A4%3C/p%3E%0A%3Cp%3E%E7%89%88%E6%9D%83%E6%89%80%E6%9C%89%3C/p%3E%0A%3Cp%3E%E9%9A%90%E7%A7%81%E6%94%BF%E7%AD%96%3Cspan%20class=%22math%20inline%22%3E%C2%A0%C2%A0%C2%A0%C2%A0%3C/span%3E%E7%94%A8%E6%88%B7%E6%9C%8D%E5%8A%A1%E5%8D%8F%E8%AE%AE%3C/p%3E%0A%3C/body%3E%0A%3C/html%3E%0A#helpen", source: data:text/html;charset=utf-8,%3C!DOCTYPE%20html%3E%0A%3Chtml%20xmlns=%22http://www.w3.org/1999/xhtml%22%20lang=%22%22%20xml:lang=%22%22%3E%0A%3Chead%3E%0A%20%20%3Cmeta%20charset=%22utf-8%22%20/%3E%0A%20%20%3Cmeta%20name=%22generator%22%20content=%22pandoc%22%20/%3E%0A%20%20%3Cmeta%20name=%22viewport%22%20content=%22width=device-width,%20initial-scale=1.0,%20user-scalable=yes%22%20/%3E%0A%20%20%3Ctitle%3E%20%3C/title%3E%0A%20%20%3Cstyle%3E%0A%20%20%20%20code%7Bwhite-space:%20pre-wrap;%7D%0A%20%20%20%20span.smallcaps%7Bfont-variant:%20small-caps;%7D%0A%20%20%20%20span.underline%7Btext-decoration:%20underline;%7D%0A%20%20%20%20div.column%7Bdisplay:%20inline-block;%20vertical-align:%20top;%20width:%2050%25;%7D%0A%20%20%20%20div.hanging-indent%7Bmargin-left:%201.5em;%20text-indent:%20-1.5em;%7D%0A%20%20%3C/style%3E%0A%20%20%3C!--%5Bif%20lt%20IE%209%5D%3E%0A%20%20%20%20%3Cscript%20src=%22//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js%22%3E%3C/script%3E%0A%20%20%3C!%5Bendif%5D--%3E%0A%20%20%3Cscript%20type=%22text/javascript%22%20src=%22help_lang.js%22%20type=%22module%22%3E%3C/script%3E%0A%20%20%3Cstyle%3E%0A%20%20/*%0A%20%20%20%20CAUTION:%20must%20use%20embedded%20style%20for%20standalone%20html%20with%20-s%0A%20%20*/%0A%20%20/***************%0A%20%20Global%0A%20%20***************/%0A%20%20/*%0A%20%20%20*%20I%20add%20this%20to%20html%20files%20generated%20with%20pandoc.%0A%20%20%20*/%0A%20%20html%20%7B%0A%20%20font-size:%20100%25;%0A%20%20overflow-y:%20scroll;%0A%20%20-webkit-text-size-adjust:%20100%25;%0A%20%20-ms-text-size-adjust:%20100%25;%0A%0A%20%20/*--scrollbarBG:%20%23CFD8DC;*/%0A%20%20--scrollbarBG:%20%232a2f39;%0A%20%20--thumbBG:%20%2390a4ae;%0A%20%20/*CAUTION:%20required%20for%20background%20parallax%20*/%0A%20%20height:%20100%25;%0A%20%20/*CAUTION%20end:%20required%20for%20background%20parallax%20*/%0A%20%20%7D%0A%20%20body%20%7B%0A%20%20color:%20%23e5e5e5;%0A%20%20font-family:%20Arial,%20Helvetica,%20sans-serif;%0A%20%20font-size:%2012px;%0A%20%20line-height:%201.7;%0A%20%20padding:%201em;%0A%20%20margin:%20auto;%0A%20%20max-width:%2042em;%0A%20%20/*CAUTION:%20required%20for%20background%20parallax%20*/%0A%20%20background:%20url('images/bg-logo.png')%20no-repeat%20top%20right,%20%232a2f39;%0A%20%20height:%20100%25;%0A%20%20background-attachment:%20fixed;%0A%20%20background-position:%20center;%0A%20%20background-repeat:%20no-repeat;%0A%20%20background-size:%20cover;%0A%20%20/*CAUTION%20end:%20required%20for%20background%20parallax*/%0A%20%20%7D%0A%20%20a%20%7B%0A%20%20color:%20%237c8694;%0A%20%20text-decoration:%20none;%0A%20%20%7D%0A%20%20a:visited%20%7B%0A%20%20color:%20%230072ae;%0A%20%20%7D%0A%20%20a:hover%20%7B%0A%20%20color:%20%2306e;%0A%20%20%7D%0A%20%20a:active%20%7B%0A%20%20color:%20%23faa700;%0A%20%20%7D%0A%20%20a:focus%20%7B%0A%20%20outline:%20thin%20dotted;%0A%20%20%7D%0A%20%20*::-moz-selection%20%7B%0A%20%20background:%20rgba(255,%20255,%200,%200.3);%
E/InputMethodManager(28987): b/117267690: Failed to get fallback IMM with expected displayId=259 actual IMM#displayId=0 view=io.flutter.plugins.webviewflutter.InputAwareWebView{b193667 VFEDHVC.. .F...... 0,0-2075,706}

Verdict

So to me this is beyond the fuss of running an http server to work around a very simple webpage doc. It is actually a much more serious bug to me.

@pedromassangocode pedromassangocode added the customer: crowd Affects or could affect many people, though not necessarily a specific customer. label Sep 9, 2020
@OnlyTarg
Copy link

OnlyTarg commented Nov 3, 2020

load asset file or local file

  webview_flutter:
    git:
      url: https://github.com/asjqkkkk/plugins.git
      path: packages/webview_flutter
      ref: webview

Assetfiles

    WebView(
      onWebViewCreated: (WebViewController controller) {
        final url = 'assets/index.html';
        controller.loadAssetHtmlFile(url);
      },
      javascriptMode: JavascriptMode.unrestricted,
    );

Localfiles

    WebView(
      onWebViewCreated: (WebViewController controller) {
        controller.loadLocalHtmlFile(filePath)
      },
      javascriptMode: JavascriptMode.unrestricted,
    );

  Future<void> downloadFile(String url) async {
    Dio dio = Dio();
    String path = (await getApplicationDocumentsDirectory()).path;
    String fileName=url.substring(url.lastIndexOf("/")+1);
    await Dio().download(url, '$path/$fileName',onReceiveProgress: (rec,total){
      progress = ((rec/total) * 100).floor();
      if(progress >= 100){
        filePath= '$path/$fileName';
      }
      setState(() {});
    });
  }

the pr link is there: flutter/plugins#2583

Thank you so much!!!!

@jing-pei
Copy link

jing-pei commented Nov 7, 2020

load asset file or local file

  webview_flutter:
    git:
      url: https://github.com/asjqkkkk/plugins.git
      path: packages/webview_flutter
      ref: webview

Assetfiles

    WebView(
      onWebViewCreated: (WebViewController controller) {
        final url = 'assets/index.html';
        controller.loadAssetHtmlFile(url);
      },
      javascriptMode: JavascriptMode.unrestricted,
    );

Localfiles

    WebView(
      onWebViewCreated: (WebViewController controller) {
        controller.loadLocalHtmlFile(filePath)
      },
      javascriptMode: JavascriptMode.unrestricted,
    );

  Future<void> downloadFile(String url) async {
    Dio dio = Dio();
    String path = (await getApplicationDocumentsDirectory()).path;
    String fileName=url.substring(url.lastIndexOf("/")+1);
    await Dio().download(url, '$path/$fileName',onReceiveProgress: (rec,total){
      progress = ((rec/total) * 100).floor();
      if(progress >= 100){
        filePath= '$path/$fileName';
      }
      setState(() {});
    });
  }

the pr link is there: flutter/plugins#2583

我使用你提供的webview_flutter可以正常访问静态html,但是当我去访问全景时,就会出现以下信息:

image

我现在不清楚是否需要对webkit进行偏好设置webkit

我使用的是controller.loadLocalHtmlFile

@asjqkkkk

@asjqkkkk
Copy link

load asset file or local file

  webview_flutter:
    git:
      url: https://github.com/asjqkkkk/plugins.git
      path: packages/webview_flutter
      ref: webview

Assetfiles

    WebView(
      onWebViewCreated: (WebViewController controller) {
        final url = 'assets/index.html';
        controller.loadAssetHtmlFile(url);
      },
      javascriptMode: JavascriptMode.unrestricted,
    );

Localfiles

    WebView(
      onWebViewCreated: (WebViewController controller) {
        controller.loadLocalHtmlFile(filePath)
      },
      javascriptMode: JavascriptMode.unrestricted,
    );

  Future<void> downloadFile(String url) async {
    Dio dio = Dio();
    String path = (await getApplicationDocumentsDirectory()).path;
    String fileName=url.substring(url.lastIndexOf("/")+1);
    await Dio().download(url, '$path/$fileName',onReceiveProgress: (rec,total){
      progress = ((rec/total) * 100).floor();
      if(progress >= 100){
        filePath= '$path/$fileName';
      }
      setState(() {});
    });
  }

the pr link is there: flutter/plugins#2583

我使用你提供的webview_flutter可以正常访问静态html,但是当我去访问全景时,就会出现以下信息:

image

我现在不清楚是否需要对webkit进行偏好设置webkit

我使用的是controller.loadLocalHtmlFile

@asjqkkkk

我不是太了解关于 全景 的相关内容, 你找找其他的办法吧 😂

@uc-dve
Copy link

uc-dve commented Jun 10, 2021

why it is not solved yet, it's being 2.5 years since the issue reported. still, there is no way in the official webview_flutter plugin to load local js, css files from asset folder in custom HTML text.

@uc-dve
Copy link

uc-dve commented Jun 18, 2021

I use this patch to my fork to open local files with webview_flutter:

diff --git a/packages/webview_flutter/android/src/main/java/io/flutter/plugins/webviewflutter/FlutterWebView.java b/packages/webview_flutter/android/src/main/java/io/flutter/plugins/webviewflutter/FlutterWebView.java
index a2bed900..83982481 100644
--- a/packages/webview_flutter/android/src/main/java/io/flutter/plugins/webviewflutter/FlutterWebView.java
+++ b/packages/webview_flutter/android/src/main/java/io/flutter/plugins/webviewflutter/FlutterWebView.java
@@ -35,6 +35,14 @@ public class FlutterWebView implements PlatformView, MethodCallHandler {
     platformThreadHandler = new Handler(context.getMainLooper());
     // Allow local storage.
     webView.getSettings().setDomStorageEnabled(true);
+    webView.getSettings().setLoadWithOverviewMode(true);
+    webView.getSettings().setUseWideViewPort(true);
+    webView.getSettings().setJavaScriptEnabled(true);
+    webView.getSettings().setAllowFileAccessFromFileURLs(true);
+    webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
+    webView.getSettings().setBuiltInZoomControls(true);
+    webView.getSettings().setDisplayZoomControls(true);
+    webView.getSettings().setSupportZoom(true);

     methodChannel = new MethodChannel(messenger, "plugins.flutter.io/webview_" + id);
     methodChannel.setMethodCallHandler(this);
diff --git a/packages/webview_flutter/ios/Classes/FlutterWebView.m b/packages/webview_flutter/ios/Classes/FlutterWebView.m
index afc2f992..3b510c0c 100644
--- a/packages/webview_flutter/ios/Classes/FlutterWebView.m
+++ b/packages/webview_flutter/ios/Classes/FlutterWebView.m
@@ -279,7 +279,20 @@ - (bool)loadUrl:(NSString*)url {
 }

 - (bool)loadUrl:(NSString*)url withHeaders:(NSDictionary<NSString*, NSString*>*)headers {
-  NSURL* nsUrl = [NSURL URLWithString:url];
+  NSURL* nsUrl = [NSURL fileURLWithPath:url];
+  if ([url.lowercaseString hasPrefix:@"file://"]) {
+    url = [url substringFromIndex:7]; // length of 'file://'
+
+    NSURL *nsUrl = [NSURL fileURLWithPath:url];
+    NSURL *readAccessToURL = [[nsUrl URLByDeletingLastPathComponent] URLByDeletingLastPathComponent];
+    NSLog(@"\nOpening as file \(nsUrl)");
+
+    [_webView loadFileURL:nsUrl allowingReadAccessToURL:readAccessToURL];
+    return true;
+  }
+
+  NSLog(@"\nOpening as URL \(nsUrl)");
+  nsUrl = [NSURL URLWithString:url];
   if (!nsUrl) {
     return false;
   }

I have tried this on android to access documentDirectory but it is not working on android SDK 30, is there anything specific I need to change for targetSDK 30.

@github-actions
Copy link

This thread has been automatically locked since there has not been any recent activity after it was closed. If you are still experiencing a similar issue, please open a new bug, including the output of flutter doctor -v and a minimal reproduction of the issue.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Dec 21, 2021
@flutter-triage-bot flutter-triage-bot bot added the package flutter/packages repository. See also p: labels. label Jul 5, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
c: new feature Nothing broken; request for a new capability customer: crowd Affects or could affect many people, though not necessarily a specific customer. p: webview The WebView plugin P3 Issues that are less important to the Flutter project package flutter/packages repository. See also p: labels.
Projects
None yet