1

背景

我使用webview_flutter 3.0.0它来呈现我正在实时创建的复杂 HTML 字符串。所以它不是从网络加载的内容。我这样做如下:

  final Completer<WebViewController> _controller =
  Completer<WebViewController>();
  late WebViewController _con;

  var finalThreadHTML;

  _loadHTML() async {

   finalThreadHTML = createComplexHTMLStringInRealTime();

    }

    _con.loadUrl(Uri.dataFromString(
        setThreadHTML(
            finalThreadHTML
        ),
        mimeType: 'text/html',
        encoding: Encoding.getByName('utf-8')
    ).toString());
  }

然后在我的用户界面中

     WebView(
      initialUrl: '',
      javascriptMode: JavascriptMode.unrestricted,
        javascriptChannels: <JavascriptChannel>[
          JavascriptChannel(
              name: 'MessageInvoker',
              onMessageReceived: (s) {
              }),
        ].toSet(),
      onWebViewCreated: (WebViewController webViewController) {
                      _con = webViewController;
                      _loadHTML();
                      },
      onProgress: (int progress) {
                            print("WebView is loading (progress : $progress%)");
                            },
      navigationDelegate: (NavigationRequest request) {
                            if (request.url.startsWith('https://www.youtube.com/')) {
                            print('blocking navigation to $request}');
                            return NavigationDecision.prevent;
                            }
                            print('allowing navigation to $request');
                            return NavigationDecision.navigate;
                            },
      onPageStarted: (String url) {
                            print('Page started loading: $url');
                            },
      onPageFinished: (String url) {
                            print('Page finished loading: $url');
                            },
      gestureNavigationEnabled: true,
    )

我的实时 HTML 字符串(createComplexHTMLStringInRealTime())看起来像这样:

String createComplexHTMLStringInRealTime(){
  return ('''
    <html>
      <head>
    
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      </head>
      
        <body style="height:100vh;">
              Testing some stuff
              <img src="/images/blankAvatar.jpg" />
              Testing more stuff
        </body>
      </html>
      
    ''');
}

我的问题

在我形成的 HTML 字符串中,我想包含一些图像,它们是 pubspec.yaml 中定义的本地资产文件

所以我试着这样做:

<img src="/images/blankAvatar.jpg" />

但这没有加载任何东西,然后我尝试了

<img src="file:///images/blankAvatar.jpg" />

依然没有。

无论如何要加载与我生成的文本内联的本地文件以将本地文件加载到 webview 中?

4

1 回答 1

0

您可以复制粘贴运行完整代码和index.html下面
您可以使用包https://pub.dev/packages/flutter_inappwebview
在工作演示中,您可以看到颤振图标<img src="images/flutter-logo.svg" alt="flutter logo">正确显示

第 1 步:添加android:usesCleartextTraffic="true"AndroidManifest.xml
2 步:pubspec.yaml设置

assets:
    - assets/images/
    - assets/

第 3 步:将文件和图像添加到assets文件夹

在此处输入图像描述

工作演示

在此处输入图像描述

完整代码

import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

InAppLocalhostServer localhostServer = new InAppLocalhostServer();

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await localhostServer.start();
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('InAppWebView Example'),
        ),
        body: Container(
            child: Column(children: <Widget>[
          Expanded(
            child: Container(
              child: InAppWebView(
                initialUrl: "http://localhost:8080/assets/index.html",
                initialHeaders: {},
                initialOptions: InAppWebViewGroupOptions(),
                onWebViewCreated: (InAppWebViewController controller) {},
                onLoadStart: (InAppWebViewController controller, String url) {},
                onLoadStop: (InAppWebViewController controller, String url) {},
              ),
            ),
          )
        ])),
      ),
    );
  }
}

索引.html

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Flutter InAppWebView</title>
    <link rel="stylesheet" href="https://getbootstrap.com/docs/4.3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="css/style.css">
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <link rel="shortcut icon" href="favicon.ico">
</head>
<body class="text-center">
    <div class="cover-container d-flex w-100 h-100 p-3 mx-auto flex-column">
        <header class="masthead mb-auto">
            <div class="inner">
                <h3 class="masthead-brand">Flutter InAppWebView</h3>
                <nav class="nav nav-masthead justify-content-center">
                    <a class="nav-link active" href="index.html">Home</a>
                    <a class="nav-link" href="page-1.html">Page 1</a>
                    <a class="nav-link" href="page-2.html">Page 2</a>
                </nav>
            </div>
        </header>

        <main role="main" class="inner cover">
            <h1 class="cover-heading">Inline WebView</h1>
            <img src="images/flutter-logo.svg" alt="flutter logo">
            <a href="index.html"><img src="images/flutter-logo.svg" alt="flutter logo"></a>
            <p class="lead">Cover is a one-page template for building simple and beautiful home pages. Download, edit the text, and add your own fullscreen background photo to make it your own.</p>
        </main>

        <footer class="mastfoot mt-auto">
            <div class="inner">
                <p>Cover template for <a target="_blank" href="https://getbootstrap.com/">Bootstrap</a>, by <a href="https://twitter.com/mdo">@mdo</a>.</p>
                <p>Phone link example <a href="tel:1-408-555-5555">1-408-555-5555</a></p>
                <p>Email link example <a href="mailto:example@gmail.com">example@gmail.com</a></p>
            </div>
        </footer>
    </div>
    <script src="js/main.js"></script>
</body>
</html>

从答案中得到这个解决方案希望它会对你有所帮助

于 2022-01-02T05:09:05.157 回答