【问题标题】:How to access local CSS, JS and Images from Flutter WebView如何从 Flutter WebView 访问本地 CSS、JS 和图像
【发布时间】:2019-11-09 06:17:40
【问题描述】:

我正在尝试在本地 HTML 文件中嵌入图像。并尝试通过颤振审查加载该 HTML 文件。正在显示网页文本,但没有显示本地引用的图像。

网络视图

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 dart


【解决方案1】:

您可以为此使用flutter_inappwebview 插件。首先在你的pubspec.yaml中定义资产目录

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

为内容交付创建本地服务器。

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

【讨论】:

    猜你喜欢
    • 2018-04-26
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多