如何从Flutter WebView访问本地CSS,JS和图像 [英] How to access local CSS, JS and Images from Flutter WebView

查看:47
本文介绍了如何从Flutter WebView访问本地CSS,JS和图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将图像嵌入本地HTML文件中.并尝试通过快速查看加载该HTML文件.该网页上的文字显示了,但是没有显示本地引用的图像.

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">

推荐答案

您可以为此使用 flutter_inappwebview 插件.首先在您的 pubspec.yaml

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();

运行服务器

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

在小部件树中添加 InAppWebView .

  @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,
            )
        ),
      ),
    );
  }

停止服务器

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

我创建了一个示例项目,您可以在这里找到 https://github.com/zakir01913/flutter_webview_with_local_assest

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

这篇关于如何从Flutter WebView访问本地CSS,JS和图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆