How to access local CSS, JS and Images from Flutter WebView

◇◆丶佛笑我妖孽 提交于 2021-01-27 05:25:28

问题


I am trying to embed an image within a local HTML file. and trying to load that HTML file through a flutter review. the web page texts are showing but no locally referred images are showing.

WebView

class _HomeState extends State<Home> {
  WebViewController _webViewController;
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.orange,
      child: WebView(
        initialUrl: "",
        javascriptMode: JavascriptMode.unrestricted,
        onWebViewCreated: (controller){
          _webViewController = controller;
          _loadHtmlFromAssets();
        },
      ),

    );
  }

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

Html

<h1>Hellop</h1>
<img src="myimage.jpg">

回答1:


You can use the flutter_inappwebview plugin for that. First define the asset directory in your pubspec.yaml

  assets:
    - assets/index.html
    - assets/img/

Create an local server for content delivery.

InAppLocalhostServer localhostServer = new InAppLocalhostServer();

Run the server

void main() async {
  await localhostServer.start();
  runApp(MyApp());
}

Add InAppWebView in your widget tree.

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: InAppWebView(
        initialUrl: "http://localhost:8080/assets/index.html",
        initialOptions: InAppWebViewWidgetOptions(
            inAppWebViewOptions: InAppWebViewOptions(
              debuggingEnabled: true,
            )
        ),
      ),
    );
  }

Stop the server

  @override
  void dispose() {
    localhostServer.close();
    super.dispose();
  }

I have created a sample project which you can find here https://github.com/zakir01913/flutter_webview_with_local_assest



来源:https://stackoverflow.com/questions/56787422/how-to-access-local-css-js-and-images-from-flutter-webview

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!