import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'dart:async';
import 'package:flutter/cupertino.dart';
class WebViewPageextends StatefulWidget {
String_title;
String_url;
WebViewPage(this._url,this._title);
@override
_WebViewPageState createState() => _WebViewPageState();
}
class _WebViewPageStateextends State {
BuildContextcontext;
// 标记是否是加载中
boolloading =true;
// 标记当前页面是否是我们自定义的回调页面
boolisLoadingCallbackPage =true;
GlobalKeyscaffoldKey =new GlobalKey();
// URL变化监听器
StreamSubscriptiononUrlChanged;
// WebView加载状态变化监听器
StreamSubscriptiononStateChanged;
// 插件提供的对象,该对象用于WebView的各种操作
FlutterWebviewPluginflutterWebViewPlugin =new FlutterWebviewPlugin();
@override
void initState() {
onStateChanged =flutterWebViewPlugin.onStateChanged.listen((WebViewStateChanged state){
// state.type是一个枚举类型,取值有:WebViewState.shouldStart, WebViewState.startLoad, WebViewState.finishLoad
switch (state.type) {
case WebViewState.shouldStart:
print('shouldStart');
print(widget._url);
print('shouldStart');
// 准备加载
setState(() {
loading =true;
});
break;
case WebViewState.startLoad:
// 开始加载
break;
case WebViewState.finishLoad:
print('finishLoad');
// 加载完成
setState(() {
loading =false;
});
if (isLoadingCallbackPage) {
// 当前是回调页面,则调用js方法获取数据
parseResult();
}
break;
}
});
}
// 解析WebView中的数据
void parseResult() {
// flutterWebViewPlugin.evalJavascript("get();").then((result) {
flutterWebViewPlugin.evalJavascript("document.documentElement.innerHTML").then((result) {
// result json字符串,包含token信息
print(result);
print('123456');
setState(() {
widget._title = result;
});
});
}
@override
Widget build(BuildContext context) {
this.context = context;
List titleContent = [];
titleContent.add(new Text(
widget._title,
style:new TextStyle(color: Colors.white),
));
if (loading) {
// 如果还在加载中,就在标题栏上显示一个圆形进度条
titleContent.add(new CupertinoActivityIndicator());
}
titleContent.add(new Container(width:50.0));
// WebviewScaffold是插件提供的组件,用于在页面上显示一个WebView并加载URL
return WillPopScope(
child: WebviewScaffold(
key:scaffoldKey,
url:widget._url,
appBar:new AppBar(
iconTheme: IconThemeData(
color: Colors.white
),
backgroundColor: Color.fromARGB(255,41,58,144),
title:new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: titleContent,
),
),
withZoom:true,// 允许网页缩放
withLocalStorage:true,// 允许LocalStorage
withJavascript:true,// 允许执行js代码
),
onWillPop: _requestPop
);
}
Future _requestPop() {
Navigator.of(context).pop(100);///弹出页面并传回int值100,用于上一个界面的回调
return new Future.value(false);
}
}