在Flutter中使用来自字符串的HTML的WebView

huangapple go评论66阅读模式
英文:

WebView in Flutter with html from a string

问题

I am trying to make an application with flutter and I need to pass html with a string to webviewer but I always get an error, I have tried this code but it tells me that the controller is not initialized, is there an easier way? The plugin's github doesn't make it clear to me. Thank you so much

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:webview_flutter/webview_flutter.dart';

class MyWebViewWidget extends StatefulWidget {
  final String html;

  MyWebViewWidget({required this.html});

  @override
  _MyWebViewWidgetState createState() => _MyWebViewWidgetState();
}

class _MyWebViewWidgetState extends State<MyWebViewWidget> {
  late WebViewController _controller;
  @override
  void initState() {
    super.initState();

    late final PlatformWebViewControllerCreationParams params;

    params = const PlatformWebViewControllerCreationParams();

    final WebViewController controller =
    WebViewController.fromPlatformCreationParams(params);

    controller
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(const Color(0x00000000))
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
            debugPrint('WebView is loading (progress : $progress%)');
          },
          onPageStarted: (String url) {
            debugPrint('Page started loading: $url');
          },
          onPageFinished: (String url) {
            debugPrint('Page finished loading: $url');
          },
          onWebResourceError: (WebResourceError error) {
            debugPrint('''
Page resource error:
  code: ${error.errorCode}
  description: ${error.description}
  errorType: ${error.errorType}
  isForMainFrame: ${error.isForMainFrame}
''');
          },
          onNavigationRequest: (NavigationRequest request) {
            if (request.url.startsWith('https://www.youtube.com/')) {
              debugPrint('blocking navigation to ${request.url}');
              return NavigationDecision.prevent;
            }
            debugPrint('allowing navigation to ${request.url}');
            return NavigationDecision.navigate;
          },
        ),
      )
      ..addJavaScriptChannel(
        'Toaster',
        onMessageReceived: (JavaScriptMessage message) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(message.message)),
          );
        },
      )
      ..loadRequest(Uri.parse('https://flutter.dev'));

    _controller = controller;
  }

  @override
  Widget build(BuildContext context) {
    return WebViewWidget(
      html: widget.html,
      controller: _controller,
    );
  }
}

class WebViewWidget extends StatelessWidget {
  final String html;
  WebViewController controller;

  WebViewWidget({required this.html, required this.controller});

  @override
  Widget build(BuildContext context) {
    return WebView(
      initialUrl: 'data:text/html;base64,' + base64Encode(const Utf8Encoder().convert('''
        <!DOCTYPE html>
        <html>
          <head>
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
          </head>
          <body>
            $html
          </body>
        </html>
      ''')),
      onWebViewCreated: (WebViewController webViewController) {
        controller = webViewController;
      },
    );
  }
}

I have tried with different plugins like flutter_webviewplus, flutter_webview_plugin: ^0.4.0, and nothing works. Besides, I can't use webview as is.

英文:

I am trying to make an application with flutter and I need to pass html with a string to webviewer but I always get an error, I have tried this code but it tells me that the controller is not initialized, is there an easier way? The plugin's github doesn't make it clear to me. Thank you so much

import &#39;package:flutter/material.dart&#39;;
import &#39;package:flutter/widgets.dart&#39;;
import &#39;package:webview_flutter/webview_flutter.dart&#39;;
class MyWebViewWidget extends StatefulWidget {
final String html;
MyWebViewWidget({required this.html});
@override
_MyWebViewWidgetState createState() =&gt; _MyWebViewWidgetState();
}
class _MyWebViewWidgetState extends State&lt;MyWebViewWidget&gt; {
late WebViewController _controller;
@override
void initState() {
super.initState();
// #docregion platform_features
late final PlatformWebViewControllerCreationParams params;
params = const PlatformWebViewControllerCreationParams();
final WebViewController controller =
WebViewController.fromPlatformCreationParams(params);
// #enddocregion platform_features
controller
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setBackgroundColor(const Color(0x00000000))
..setNavigationDelegate(
NavigationDelegate(
onProgress: (int progress) {
debugPrint(&#39;WebView is loading (progress : $progress%)&#39;);
},
onPageStarted: (String url) {
debugPrint(&#39;Page started loading: $url&#39;);
},
onPageFinished: (String url) {
debugPrint(&#39;Page finished loading: $url&#39;);
},
onWebResourceError: (WebResourceError error) {
debugPrint(&#39;&#39;&#39;
Page resource error:
code: ${error.errorCode}
description: ${error.description}
errorType: ${error.errorType}
isForMainFrame: ${error.isForMainFrame}
&#39;&#39;&#39;);
},
onNavigationRequest: (NavigationRequest request) {
if (request.url.startsWith(&#39;https://www.youtube.com/&#39;)) {
debugPrint(&#39;blocking navigation to ${request.url}&#39;);
return NavigationDecision.prevent;
}
debugPrint(&#39;allowing navigation to ${request.url}&#39;);
return NavigationDecision.navigate;
},
),
)
..addJavaScriptChannel(
&#39;Toaster&#39;,
onMessageReceived: (JavaScriptMessage message) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(message.message)),
);
},
)
..loadRequest(Uri.parse(&#39;https://flutter.dev&#39;));
// #docregion platform_features
// #enddocregion platform_features
_controller = controller;
}
@override
Widget build(BuildContext context) {
return WebViewWidget(
html: widget.html,
controller: _controller,
);
}
}
class WebViewWidget extends StatelessWidget {
final String html;
WebViewController controller;
WebViewWidget({required this.html, required this.controller});
@override
Widget build(BuildContext context) {
return WebViewWidget(
html: &#39;&#39;&#39;
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
&lt;/head&gt;
&lt;body&gt;
$html
&lt;/body&gt;
&lt;/html&gt;
&#39;&#39;&#39;,
controller: controller,
);
}
}

He probado con diferentes plugins como flutter_webviewplus, flutter_webview_plugin: ^0.4.0 y nada, además webview tal cual no me deja usarlo.

答案1

得分: 1

我也在我的应用程序中的 WebView 中显示一个静态 HTML 字符串。但我是以不同的方式实例化 WebView 控制器的,并使用控制器的 loadHtmlString 函数加载 HTML。

控制器

WebViewController wbController = WebViewController()
	..enableZoom(true)
	..setJavaScriptMode(JavaScriptMode.unrestricted)
	..setBackgroundColor(const Color(0x00000000))
	..setNavigationDelegate(
	  NavigationDelegate(
		onNavigationRequest: (NavigationRequest request) {
		  if (request.url.startsWith("https://")) {
			launchUrl(Uri.parse(request.url));
			return NavigationDecision.navigate;
		  } else {
			return NavigationDecision.prevent;
		  }
		},
	  ),
	)
	..loadHtmlString("""
	  <!DOCTYPE html>
		<html>
		  <head><meta name="viewport" content="width=device-width, initial-scale=0.7"></head>
		  <body style='margin: 0; padding: 0;'>
			${html.content}
		  </body>
		</html>
	""");

WebView

WebViewWidget(
    controller: wbController,
)
英文:

I'm also showing a static html string in a webview in my application. But I'm instantiating the webview controller in a different way, and loading the html with the loadHtmlString function from controller.

Controller

WebViewController wbController = WebViewController()
..enableZoom(true)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setBackgroundColor(const Color(0x00000000))
..setNavigationDelegate(
NavigationDelegate(
onNavigationRequest: (NavigationRequest request) {
if (request.url.startsWith(&quot;https://&quot;)) {
launchUrl(Uri.parse(request.url));
return NavigationDecision.navigate;
} else {
return NavigationDecision.prevent;
}
},
),
)
..loadHtmlString(&quot;&quot;&quot;
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=0.7&quot;&gt;&lt;/head&gt;
&lt;body style=&#39;&quot;margin: 0; padding: 0;&#39;&gt;
${html.content}
&lt;/body&gt;
&lt;/html&gt;
&quot;&quot;&quot;);

Webview

WebViewWidget(
controller: wbController,
)

huangapple
  • 本文由 发表于 2023年4月4日 03:27:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75923116.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定