Flutter之Webview組件

https://pub.flutter-io.cn/packages/flutter_webview_plugin

/**
 *
 * const WebviewScaffold({
    Key key,
    this.appBar,
    @required this.url,
    this.headers,//
    this.withJavascript,//是否允許執(zhí)行js代碼
    this.clearCache,//
    this.clearCookies,//
    this.enableAppScheme,//
    this.userAgent,//
    this.primary = true,//
    this.persistentFooterButtons,//
    this.bottomNavigationBar,//
    this.withZoom,//是否允許網(wǎng)頁縮放
    this.withLocalStorage,//是否允許LocalStorage
    this.withLocalUrl,//
    this.scrollBar,//是否顯示滾動(dòng)條
    this.supportMultipleWindows,//
    this.appCacheEnabled,//
    this.hidden = false,//
    this.initialChild,//
    this.allowFileURLs,//
    this.resizeToAvoidBottomInset = false,//
    this.invalidUrlRegex,//
    this.geolocationEnabled//
    })
 */

import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:http/http.dart' as http;

class Widget_WebView_Page extends StatefulWidget {

  @override
  State<StatefulWidget> createState() {
    return Widget_WebView_State();
  }

}

class Widget_WebView_State extends State<Widget_WebView_Page>
    with SingleTickerProviderStateMixin {
  FlutterWebviewPlugin flutterWebviewPlugin = FlutterWebviewPlugin();
  var title = "WebView組件";
  var tabs;
  TabController controller;
  var choiceIndex = 0;

  //獲取h5頁面標(biāo)題
  Future<String> getWebTitle() async {
    String script = 'window.document.title';
    var title = await
    flutterWebviewPlugin.evalJavascript(script);
    setState(() {
      this.title = title;
      print('####################   $title');
    });
  }

  //獲取h5頁面標(biāo)題
  Future<String> getWebTitle2({String url}) async {
    var client = http.Client();
    client
        .get(url)
        .then(
            (response) {
          String title = RegExp(
              r"<[t|T]{1}[i|I]{1}[t|T]{1}[l|L]{1}[e|E]{1}(\s.*)?>([^<]*)</[t|T]{1}[i|I]{1}[t|T]{1}[l|L]{1}[e|E]{1}>")
              .stringMatch(response.body);
          if (title != null) {
            title =
                title.substring(title.indexOf('>') + 1, title.lastIndexOf("<"));
          } else {
            title = "";
          }
          print("####################  " + title);
        })
        .catchError(
            (error) {
          print(error);
        })
        .whenComplete(client.close,);
  }


  @override
  void initState() {
    super.initState();

    /**
     * 監(jiān)聽web頁加載狀態(tài)
     */
    flutterWebviewPlugin.onStateChanged.listen((
        WebViewStateChanged webViewState) async {
//      setState(() {
//        title = webViewState.type.toString();
//      });
      switch (webViewState.type) {
        case WebViewState.finishLoad:
          handleJs();

          getWebTitle();

          break;
        case WebViewState.shouldStart:
          break;
        case WebViewState.startLoad:
          break;
        case WebViewState.abortLoad:
          break;
      }
    });

    /**
     * 監(jiān)聽頁面加載url
     */
    flutterWebviewPlugin.onUrlChanged.listen((String url) {
//      getWebTitle(url: url);

//      setState(() {
//        title = url;
//      });
    });

    /**
     * 監(jiān)聽x軸滑動(dòng)距離
     * 好像沒什么用
     */
//    flutterWebviewPlugin.onScrollXChanged.listen((double offsetX) {
//      title = offsetX.toString();
//    });

//    flutterWebviewPlugin.onScrollYChanged.listen((double offsetY) {
//      title = offsetY.toString();
//    });

    tabs = <Widget>[
      Tab(
        child: GestureDetector(
          child: Text("刷新"),
          onTap: () {
            flutterWebviewPlugin.reload();
          },
        ),
      ),
      Tab(
        child: GestureDetector(
          child: Text("返回"),
          onTap: () {
            flutterWebviewPlugin.goBack();
          },
        ),
      ),
      Tab(
        child: GestureDetector(
          child: Text("加載指定url"),
          onTap: () {
            flutterWebviewPlugin.reloadUrl("https://www.360.com");
          },
        ),
      ),
    ];
    controller =
        TabController(initialIndex: 0, length: tabs.length, vsync: this);
  }

  @override
  Widget build(BuildContext context) {
    return WebviewScaffold(
      url: "http://www.baidu.com",
      //默認(rèn)加載地址
      appBar: AppBar(
        title: Text(title),
        backgroundColor: Colors.grey,
        leading: GestureDetector(
          child: Icon(Icons.arrow_back),
          onTap: () {
            flutterWebviewPlugin.close();
          },
        ),
        bottom: TabBar(
          tabs: tabs,
          controller: controller,
          indicatorColor: Colors.red,
        ),
        actions: <Widget>[
        ],
      ),
      bottomNavigationBar: BottomNavigationBar(
          items: [
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              title: Text(
                "首頁", /*style: TextStyle(color: Color(0xff333333)),*/),
              activeIcon: Icon(
                Icons.home,
                color: Color(0xffDE331F),
//                size: 30.0,
              ),
              backgroundColor: Color(0xffff0000),
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.devices_other),
              title: Text(
                "其他", /*style: TextStyle(color: Color(0xff333333)),*/),
              activeIcon: Icon(
                Icons.devices_other,
                color: Color(0xffDE331F),
//                size: 30.0,
              ),
              backgroundColor: Color(0xffff0000),
            ),
          ],
          currentIndex: choiceIndex,
          fixedColor: Color(0xffDE331F),
//          iconSize: 30.0,
//          type: BottomNavigationBarType.fixed,
          onTap: (index) {
            if (index == 0) {
              setState(() {
                choiceIndex = 0;
                flutterWebviewPlugin.reloadUrl("https://www.qq.com/");
              });
            } else {
              setState(() {
                flutterWebviewPlugin.reloadUrl("https://www.alipay.com/");
                choiceIndex = 1;
              });
            }
          }

      ),
      scrollBar: false,
      withZoom: false,
    );
  }

  @override
  void dispose() {
    flutterWebviewPlugin.dispose();
    super.dispose();
  }

  void handleJs() {
    flutterWebviewPlugin.evalJavascript(
        "abc(${title}')")
        .then((result) {

    });
  }
}


/**
 *
 * const WebviewScaffold({
    Key key,
    this.appBar,
    @required this.url,
    this.headers,//
    this.withJavascript,//是否允許執(zhí)行js代碼
    this.clearCache,//
    this.clearCookies,//
    this.enableAppScheme,//
    this.userAgent,//
    this.primary = true,//
    this.persistentFooterButtons,//
    this.bottomNavigationBar,//
    this.withZoom,//是否允許網(wǎng)頁縮放
    this.withLocalStorage,//是否允許LocalStorage
    this.withLocalUrl,//
    this.scrollBar,//是否顯示滾動(dòng)條
    this.supportMultipleWindows,//
    this.appCacheEnabled,//
    this.hidden = false,//
    this.initialChild,//
    this.allowFileURLs,//
    this.resizeToAvoidBottomInset = false,//
    this.invalidUrlRegex,//
    this.geolocationEnabled//
    })
 */

碼云地址:https://gitee.com/xgljh/Flutter.git

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容