一步一步搭建Flutter开发架子-WebView

2,412 阅读2分钟

自己原来是做iOS开发,后来转成react-native,iOS中的webview还好,最新的WkWebView兼容性还行。但是遇到android的时候,真的是被各种的手机支配的心累。这篇文章主要说下webView在Flutter中怎么使用。找到最适合项目的方案

webview_flutter

On iOS the WebView widget is backed by a WKWebView; On Android the WebView widget is backed by a WebView.

引入库在pubspec.yaml中加入。没有用最新版本,还没更新到2.0

webview_flutter: ^1.0.7

这个插件是官方推荐的使用也比较简单

import 'package:webview_flutter/webview_flutter.dart';

@override
  void initState() {
    super.initState();
    if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();
  }

  @override
  Widget build(BuildContext context) {
    return WebView(
      initialUrl: 'https://flutter.dev',
    );
  }

控制webView的展示的宽高:

@override
  Widget build(BuildContext context) {
    return UnconstrainedBox(
      child: Container(
          height: 300,
          width: 300,
          child: WebView(
            initialUrl: 'https://flutter.dev',
          )),
    );
  }

加载本地html文件

WebViewController _webViewController;

WebView(
 initialUrl: '',
 javascriptMode: JavascriptMode.unrestricted,
 onWebViewCreated: (WebViewController webViewController) {
   _webViewController = webViewController;
    _loadHtmlFromAssets();
  },
)

_loadHtmlFromAssets() async {
  String fileHtmlContents = await rootBundle.loadString('本地路径html文件在项目中的路径');
  _webViewController.loadUrl(Uri.dataFromString(fileHtmlContents,
  mimeType: 'text/html', encoding: Encoding.getByName('utf-8')).toString());
 }

据说flutter_webview_plugin这个插件是在webview_flutter基础上做的封装,有兴趣的可以看下。这些都不是重点。这两个可以插件可以说在iOS上没有问题,但是在android上呢,随着碎片化的机型适配,我遇到的比较特殊的局势oppo和vivo手机上适配不太行,需要腾讯X5内核的才行。

x5_webview

针对于android的加载webView的解决方案。 同样pubspec.yaml文件添加

x5_webview: ^0.24.6

插件介绍android6.0以上需要动态申请权限, 使用permission_handler库进行申请权限

//请求权限
Map<Permission, PermissionStatus> statuses = await [
      Permission.phone,
      Permission.storage,
    ].request();
//判断权限
if (!(statuses[Permission.phone].isGranted &&
statuses[Permission.storage].isGranted)) {
    print("权限被拒绝");
    return;
}

初始化:

var isOk = await X5Sdk.init();
print(isOk ? "X5内核成功加载" : "X5内核加载失败");

支持直接打开页面

X5Sdk.openWebActivity("https://www.baidu.com",title: "web页面");

内嵌webView:

X5WebView(
  url: "https://www.baidu.com",
  javaScriptEnabled: true,
  header: {"TestHeader": "测试"},
  userAgentString: "my_ua",
 //Url拦截,传null不会拦截会自动跳转
 onUrlLoading: (willLoadUrl) {
      _controller.loadUrl(willLoadUrl);
 }
 onWebViewCreated: (control) {
      _controller = control;
},)

仅对与android平台

flutter_html

如果项目中遇到,直接返回html的数据,直接使用flutter_html展示即可, 同样的方式引入

flutter_html: ^1.1.1

@override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('flutter_html'),
        ),
        body: Html(data: """
    <h1>Table support:</h1>
    <table>
    <colgroup>
    <col width="50%" />
    <col span="2" width="25%" />
    </colgroup>
    <thead>
    <tr><th>One</th><th>Two</th><th>Three</th></tr>
    </thead>
    <tbody>
    <tr>
    <td rowspan='2'>Rowspan\nRowspan\nRowspan\nRowspan\nRowspan\nRowspan\nRowspan\nRowspan\nRowspan\nRowspan</td><td>Data</td><td>Data</td>
    </tr>
    <tr>
    <td colspan="2"><img alt='Google' src='https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png' /></td>
    </tr>
    </tbody>
    <tfoot>
    <tr><td>fData</td><td>fData</td><td>fData</td></tr>
    </tfoot>
    </table>""", style: {
          // tables will have the below background color
          "table": Style(
            backgroundColor: Color.fromARGB(0x50, 0xee, 0xee, 0xee),
          ),
          // some other granular customizations are also possible
          "tr": Style(
            border: Border(bottom: BorderSide(color: Colors.grey)),
          ),
          "th": Style(
            padding: EdgeInsets.all(6),
            backgroundColor: Colors.grey,
          ),
          "td": Style(
            padding: EdgeInsets.all(6),
            alignment: Alignment.topLeft,
          ),
          // text that renders h1 elements will be red
          "h1": Style(color: Colors.red),
        }));
  }

加载自定义的富文本 线上编译器编辑富文本 实际显示如下:

flutter_fai_webview 也可以这里不一一说了,感兴趣的可以看一下,选择一款适合自己的

one more things.....

  • 图表展示

欢迎大家来讨论。。。。。。