先看效果圖
然后是代碼
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:wanandroid/utils/ScreenUtils.dart';
import 'package:webview_flutter/webview_flutter.dart';
class WebViewBrowser extends StatefulWidget{
@override
_WebViewBrowserState createState() {
return _WebViewBrowserState();
}
}
class _WebViewBrowserState extends State<WebViewBrowser>{
/// 當前頁的標題
String _title = "";
/// 獲取當前標題
void _getNavTitle() async {
_title = _webViewController!=null ? await _webViewController.getTitle():"";
}
/// WebViewController對象
WebViewController _webViewController;
/// 頁面加載結束
bool _loadingEnded = true;
/// 是否可以返回
bool _canGoBack = false;
/// 操作面板按鈕
IconButton _shareButton;
@override
void initState() {
super.initState();
_loadingEnded = true;
_canGoBack = false;
/// 根據加載狀態(tài)顯示分享按鈕還是進度提示
_shareButton = IconButton(icon: Icon(Icons.more_horiz_rounded), onPressed: (){
_operationAction();
});
}
@override
Widget build(BuildContext context) {
var _url = (ModalRoute.of(context).settings.arguments).toString() ?? "https://www.baidu.com";
return Scaffold(
appBar: AppBar(
brightness: Brightness.dark,
automaticallyImplyLeading: true,
toolbarHeight: Screen.navigationBarHeight,
elevation: 1,
title: _loadingEnded?Text(_title,style: TextStyle(fontSize: 14),maxLines: 2):CupertinoActivityIndicator(),
centerTitle: false,
leadingWidth: 54,
/// 返回按鍵
leading: IconButton(icon: Icon(Icons.arrow_back), onPressed: () async {
if(_canGoBack == true){
_webViewController.goBack();
}else{
if(Navigator.canPop(context)){ Navigator.pop(context); }
}
}),
/// 分享按鈕和關閉按鈕
actions: _canGoBack==true?[
//關閉當前頁面
IconButton(icon: Icon(Icons.close), onPressed: (){
if(Navigator.canPop(context)){ Navigator.pop(context); }
}),
// 彈出操作面板
_shareButton
]:[ _shareButton ]
),
body: WebView(
initialUrl: _url,
javascriptMode: JavascriptMode.unrestricted,
gestureNavigationEnabled: true,
debuggingEnabled: true,
onWebViewCreated: (webViewController)async{
_webViewController = webViewController;
_loadingEnded = false;
_canGoBack = await _webViewController.canGoBack();
_getNavTitle();
setState(() {
});
},
onPageStarted: (currentUrl)async{
_loadingEnded = false;
_title = currentUrl;
_canGoBack = await _webViewController.canGoBack();
_getNavTitle();
setState(() {
});
},
onPageFinished: (currentUrl) async{
_loadingEnded = true;
_canGoBack = await _webViewController.canGoBack();
_getNavTitle();
setState(() {
});
},
onWebResourceError: (error){
_title = error.description;
setState(() {
});
},
navigationDelegate: (delegate){
// if (delegate.url.startsWith('alipay:') ||
// delegate.url.startsWith('weixin:')) {
// return NavigationDecision.prevent;
// }
return NavigationDecision.navigate;
},
),
);
}
@override
void dispose() {
super.dispose();
}
/// 在這里顯示操作面板
void _operationAction(){
}
}
Flutter小白歡迎各位大佬進行指教溅呢,謝謝了琢唾。