TF-261 Migrate to webview_flutter

This commit is contained in:
dab246
2022-02-17 15:04:52 +07:00
committed by Dat H. Pham
parent 1301a9c114
commit 541cdb64f5
2 changed files with 115 additions and 91 deletions
@@ -1,10 +1,13 @@
import 'dart:async';
import 'package:core/core.dart'; import 'package:core/core.dart';
import 'package:easy_web_view/easy_web_view.dart'; import 'package:easy_web_view/easy_web_view.dart';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart'; import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:url_launcher/url_launcher.dart' as launcher; import 'package:url_launcher/url_launcher.dart' as launcher;
import 'package:webview_flutter/webview_flutter.dart';
import 'dart:developer' as developer;
class HtmlContentViewer extends StatefulWidget { class HtmlContentViewer extends StatefulWidget {
@@ -14,16 +17,17 @@ class HtmlContentViewer extends StatefulWidget {
final double? heightContent; final double? heightContent;
final Widget? loadingWidget; final Widget? loadingWidget;
/// Register this callback if you want a reference to the [InAppWebViewController]. /// Register this callback if you want a reference to the [WebViewController].
final void Function(InAppWebViewController controller)? onCreated; final void Function(WebViewController controller)? onCreated;
final void Function(InAppWebViewController controller, Uri? uri)? onLoadStart;
final void Function(InAppWebViewController controller, Uri? uri)? onLoadStop;
/// Handler for mailto: links /// Handler for mailto: links
final Future Function(Uri mailto)? mailtoDelegate; final Future Function(Uri mailto)? mailtoDelegate;
/// Handler for any non-media URLs that the user taps on the website.
///
/// Returns `true` when the given `url` was handled.
final Future<bool> Function(String url)? urlLauncherDelegate;
const HtmlContentViewer({ const HtmlContentViewer({
Key? key, Key? key,
required this.contentHtml, required this.contentHtml,
@@ -32,8 +36,7 @@ class HtmlContentViewer extends StatefulWidget {
this.minHeight = 100, this.minHeight = 100,
this.loadingWidget, this.loadingWidget,
this.onCreated, this.onCreated,
this.onLoadStart, this.urlLauncherDelegate,
this.onLoadStop,
this.mailtoDelegate, this.mailtoDelegate,
}) : super(key: key); }) : super(key: key);
@@ -43,16 +46,17 @@ class HtmlContentViewer extends StatefulWidget {
class _HtmlContentViewState extends State<HtmlContentViewer> { class _HtmlContentViewState extends State<HtmlContentViewer> {
double? _documentHeight = 1.0; double? _webViewHeight = 1.0;
double? _documentWidth = 1.0; double? _webViewWidth = 1.0;
String? _initialPageContent; String? _htmlData;
late InAppWebViewController _webViewController; late WebViewController _webViewController;
bool loading = true; // late EasyWebViewControllerWrapperBase _easyWebViewControllerWrapperBase;
bool _isLoading = true;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_initialPageContent = _generateHtmlDocument(widget.contentHtml); _htmlData = _generateHtmlDocument(widget.contentHtml);
} }
String _generateHtmlDocument(String content) { String _generateHtmlDocument(String content) {
@@ -103,18 +107,24 @@ class _HtmlContentViewState extends State<HtmlContentViewer> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
if (kIsWeb) { if (kIsWeb) {
return _buildWebViewOnBrowser(); return Stack(
alignment: AlignmentDirectional.center,
children: [
_buildWebViewOnBrowser(),
if (_isLoading) _buildLoadingView()
],
);
} else { } else {
_documentWidth = widget.widthContent; _webViewWidth = widget.widthContent;
return Stack( return Stack(
alignment: AlignmentDirectional.center, alignment: AlignmentDirectional.center,
children: [ children: [
SizedBox( SizedBox(
height: _documentHeight, height: _webViewHeight,
width: _documentWidth, width: _webViewWidth,
child: _buildWebView(), child: _buildWebView(),
), ),
if (loading) _buildLoadingView() if (_isLoading) _buildLoadingView()
], ],
); );
} }
@@ -134,99 +144,113 @@ class _HtmlContentViewState extends State<HtmlContentViewer> {
} }
Widget _buildWebViewOnBrowser() { Widget _buildWebViewOnBrowser() {
if (_initialPageContent == null || _initialPageContent?.isEmpty == true) { final htmlData = _htmlData;
if (htmlData == null || htmlData.isEmpty) {
return Container(); return Container();
} }
return EasyWebView( return EasyWebView(
key: ValueKey('WebViewOnBrowser'), key: ValueKey(htmlData),
src: _initialPageContent!, src: htmlData,
onLoaded: () => {}, onLoaded: (controller) async {
// _easyWebViewControllerWrapperBase = controller;
if (mounted && _isLoading) {
setState(() {
_isLoading = false;
});
}
},
isHtml: true, isHtml: true,
webNavigationDelegate: (_) => WebNavigationDecision.prevent,
height: widget.heightContent, height: widget.heightContent,
webNavigationDelegate: _onNavigationOnWebBrowser,
); );
} }
Widget _buildWebView() { Widget _buildWebView() {
if (_initialPageContent == null || _initialPageContent?.isEmpty == true) { final htmlData = _htmlData;
if (htmlData == null || htmlData.isEmpty) {
return Container(); return Container();
} }
return InAppWebView( return WebView(
key: ValueKey(_initialPageContent), key: ValueKey(htmlData),
initialData: InAppWebViewInitialData(data: _initialPageContent!), javascriptMode: JavascriptMode.unrestricted,
initialOptions: InAppWebViewGroupOptions( backgroundColor: Colors.white,
crossPlatform: InAppWebViewOptions( onWebViewCreated: (controller) async {
useShouldOverrideUrlLoading: true, _webViewController = controller;
verticalScrollBarEnabled: false, developer.log('onWebViewCreated(): html: $htmlData', name: 'HtmlContentViewer');
disableVerticalScroll: false, await controller.loadHtmlString(htmlData, baseUrl: null);
disableHorizontalScroll: false, widget.onCreated?.call(controller);
supportZoom: true,
),
android: AndroidInAppWebViewOptions(
useWideViewPort: false,
loadWithOverviewMode: true,
useHybridComposition: true,
),
ios: IOSInAppWebViewOptions(
enableViewportScale: false,
allowsLinkPreview: false
),
),
onLoadStart: (controller, uri) {
if (widget.onLoadStart != null) {
widget.onLoadStart!(controller, uri);
}
}, },
onWebViewCreated: _onWebViewCreated, onPageFinished: (url) async {
onLoadStop: (controller, uri) async { final scrollHeightText = await _webViewController.runJavascriptReturningResult('document.body.scrollHeight');
final scrollHeight = await _webViewController.evaluateJavascript(source: 'document.body.scrollHeight'); final scrollHeight = double.tryParse(scrollHeightText);
if ((scrollHeight != null) && mounted && (scrollHeight + 30.0 > widget.minHeight)) { developer.log('onPageFinished(): scrollHeightText: $scrollHeightText', name: 'HtmlContentViewer');
final scrollWidthText = await _webViewController.runJavascriptReturningResult('document.body.scrollWidth');
// var scrollWidth = double.tryParse(scrollWidthText);
developer.log('onPageFinished(): scrollWidthText: $scrollWidthText', name: 'HtmlContentViewer');
if ((scrollHeight != null) && mounted) {
final scrollHeightWithBuffer = scrollHeight + 30.0;
if (scrollHeightWithBuffer > widget.minHeight) {
setState(() {
_webViewHeight = scrollHeightWithBuffer;
_isLoading = false;
});
}
}
if (mounted && _isLoading) {
setState(() { setState(() {
_documentHeight = (scrollHeight + 30.0); _isLoading = false;
}); });
} }
setState(() {
loading = false;
});
if (widget.onLoadStop != null) {
widget.onLoadStop!(controller, uri);
}
}, },
onScrollChanged: (controller, x, y) { navigationDelegate: _onNavigation,
if (y != 0) {
controller.scrollTo(x: 0, y: 0);
}
},
shouldOverrideUrlLoading: _shouldOverrideUrlLoading,
gestureRecognizers: { gestureRecognizers: {
Factory<LongPressGestureRecognizer>(() => LongPressGestureRecognizer()), Factory<LongPressGestureRecognizer>(() => LongPressGestureRecognizer()),
}, },
); );
} }
void _onWebViewCreated(InAppWebViewController controller) { FutureOr<NavigationDecision> _onNavigation(NavigationRequest navigation) async {
_webViewController = controller; developer.log('_onNavigation()', name: 'HtmlContentViewer');
if (widget.onCreated != null) { // for iOS / WKWebView necessary:
widget.onCreated!(_webViewController); if (navigation.isForMainFrame && navigation.url == 'about:blank') {
return NavigationDecision.navigate;
} }
} final requestUri = Uri.parse(navigation.url);
Future<NavigationActionPolicy> _shouldOverrideUrlLoading(
InAppWebViewController controller,
NavigationAction request
) async {
final requestUri = request.request.url!;
final mailtoHandler = widget.mailtoDelegate; final mailtoHandler = widget.mailtoDelegate;
if (mailtoHandler != null && requestUri.isScheme('mailto')) { if (mailtoHandler != null && requestUri.isScheme('mailto')) {
await mailtoHandler(requestUri); await mailtoHandler(requestUri);
return NavigationActionPolicy.CANCEL; return NavigationDecision.prevent;
} }
final url = requestUri.toString(); final url = navigation.url;
if (await launcher.canLaunch(url)) { final urlDelegate = widget.urlLauncherDelegate;
await launcher.launch(url); if (urlDelegate != null) {
return NavigationActionPolicy.CANCEL; final handled = await urlDelegate(url);
} else { if (handled) {
return NavigationActionPolicy.ALLOW; return NavigationDecision.prevent;
}
} }
await launcher.launch(url);
return NavigationDecision.prevent;
}
FutureOr<WebNavigationDecision> _onNavigationOnWebBrowser(WebNavigationRequest navigation) async {
developer.log('_onNavigationOnWebBrowser()', name: 'HtmlContentViewer');
final requestUri = Uri.parse(navigation.url);
final mailtoHandler = widget.mailtoDelegate;
if (mailtoHandler != null && requestUri.isScheme('mailto')) {
await mailtoHandler(requestUri);
return WebNavigationDecision.prevent;
}
final url = navigation.url;
final urlDelegate = widget.urlLauncherDelegate;
if (urlDelegate != null) {
final handled = await urlDelegate(url);
if (handled) {
return WebNavigationDecision.prevent;
}
}
await launcher.launch(url);
return WebNavigationDecision.prevent;
} }
} }
+5 -5
View File
@@ -61,17 +61,17 @@ dependencies:
# getwidget # getwidget
getwidget: 2.0.4 getwidget: 2.0.4
# flutter_inappwebview # webview_flutter
flutter_inappwebview: webview_flutter: 3.0.0
git:
url: https://github.com/robert-virkus/flutter_inappwebview.git
# easy_web_view: Display html for web browser
easy_web_view: easy_web_view:
git: git:
url: https://github.com/dab246/easy_web_view.git url: https://github.com/dab246/easy_web_view.git
ref: easy_web_improvements
# url_launcher # url_launcher
url_launcher: 6.0.12 url_launcher: 6.0.17
dev_dependencies: dev_dependencies:
flutter_test: flutter_test: