webview_page.dart
2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:Parlando/res/gaps.dart';
import 'package:Parlando/util/device_utils.dart';
import 'package:Parlando/widgets/my_app_bar.dart';
import 'package:webview_flutter/webview_flutter.dart';
class WebViewPage extends StatefulWidget {
const WebViewPage({
Key? key,
required this.title,
required this.url,
}) : super(key: key);
final String title;
final String url;
@override
_WebViewPageState createState() => _WebViewPageState();
}
class _WebViewPageState extends State<WebViewPage> {
final Completer<WebViewController> _controller =
Completer<WebViewController>();
int _progressValue = 0;
@override
void initState() {
super.initState();
// Enable hybrid composition.
if (Device.isAndroid) {
WebView.platform = SurfaceAndroidWebView();
}
}
@override
Widget build(BuildContext context) {
return FutureBuilder<WebViewController>(
future: _controller.future,
builder: (context, snapshot) {
return WillPopScope(
onWillPop: () async {
if (snapshot.hasData) {
final bool canGoBack = await snapshot.data!.canGoBack();
if (canGoBack) {
// 网页可以返回时,优先返回上一页
await snapshot.data!.goBack();
return Future.value(false);
}
}
return Future.value(true);
},
child: Scaffold(
appBar: const MyAppBar(),
body: Stack(
children: [
WebView(
initialUrl: widget.url,
javascriptMode: JavascriptMode.unrestricted,
allowsInlineMediaPlayback: true,
onWebViewCreated: (WebViewController webViewController) {
_controller.complete(webViewController);
},
onProgress: (int progress) {
debugPrint('WebView is loading (progress : $progress%)');
setState(() {
_progressValue = progress;
});
},
),
if (_progressValue != 100)
LinearProgressIndicator(
value: _progressValue / 100,
backgroundColor: Colors.transparent,
minHeight: 2,
)
else
Gaps.empty,
],
),
),
);
});
}
}