Blame view

lib/common/pages/wow_web_page.dart 10.6 KB
4b858f67   吴启风   feat:webview库替换
1
2
  import 'dart:collection';
  
bfb40cd0   liangchengyou   feat:忘记密码获取验证码
3
  import 'package:flutter/material.dart';
4b858f67   吴启风   feat:webview库替换
4
5
6
7
  import 'package:flutter_inappwebview/flutter_inappwebview.dart';
  import 'package:flutter_screenutil/flutter_screenutil.dart';
  import 'package:url_launcher/url_launcher.dart';
  import 'package:wow_english/common/extension/string_extension.dart';
bfb40cd0   liangchengyou   feat:忘记密码获取验证码
8
9
  import 'package:wow_english/common/widgets/we_app_bar.dart';
  
4b858f67   吴启风   feat:webview库替换
10
11
  import '../../utils/log_util.dart';
  
bfb40cd0   liangchengyou   feat:忘记密码获取验证码
12
  class WowWebViewPage extends StatefulWidget {
4b858f67   吴启风   feat:webview库替换
13
    WowWebViewPage({super.key, required this.urlStr, required this.webViewTitle});
bfb40cd0   liangchengyou   feat:忘记密码获取验证码
14
15
  
    final String urlStr;
4b858f67   吴启风   feat:webview库替换
16
    String webViewTitle;
bfb40cd0   liangchengyou   feat:忘记密码获取验证码
17
18
19
20
21
22
23
  
    @override
    State<StatefulWidget> createState() {
      return _WowWebViewPageState();
    }
  }
  
4b858f67   吴启风   feat:webview库替换
24
25
26
27
28
29
30
31
32
  /// 生成进度条组件,进度从0 ~ 1
  _createProgressBar(double progress, BuildContext context) {
    return LinearProgressIndicator(
      backgroundColor: Colors.white70.withOpacity(0),
      value: progress == 1.0 ? 0 : progress,
      valueColor: const AlwaysStoppedAnimation<Color>(Colors.blue),
    );
  }
  
bfb40cd0   liangchengyou   feat:忘记密码获取验证码
33
  class _WowWebViewPageState extends State<WowWebViewPage> {
4b858f67   吴启风   feat:webview库替换
34
35
36
37
38
39
40
    late InAppWebViewController? _inAppWebViewController;
    final GlobalKey webViewKey = GlobalKey();
    double _progress = 0;
    bool isCanGoBack = false;
    bool isCanForward = false;
    late final String defaultWebViewTitle = widget.webViewTitle;
    final String TAG = "WowWebViewPage";
bfb40cd0   liangchengyou   feat:忘记密码获取验证码
41
  
4b858f67   吴启风   feat:webview库替换
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
    // InAppWebViewSettings webViewSettings = InAppWebViewSettings(
    //   useShouldOverrideUrlLoading: true,
    //   mediaPlaybackRequiresUserGesture: true,
    //
    //   /// android 支持HybridComposition
    //   useHybridComposition: true,
    //   allowsInlineMediaPlayback: true,
    // );
    InAppWebViewGroupOptions webViewSettings = InAppWebViewGroupOptions(
      crossPlatform: InAppWebViewOptions(
        useShouldOverrideUrlLoading: true, // 是否需要跳转
        mediaPlaybackRequiresUserGesture: false, // 设置为true,防止H5的音频自动播放
        transparentBackground: true,
      ),
      android: AndroidInAppWebViewOptions(
          useHybridComposition: true,
          mixedContentMode: AndroidMixedContentMode.MIXED_CONTENT_ALWAYS_ALLOW),
      ios: IOSInAppWebViewOptions(
        allowsInlineMediaPlayback: true,
      ),
    );
  
    Future<String?> getUrl() {
      if (_inAppWebViewController == null) {
        return Future.sync(() => null);
      }
      return _inAppWebViewController!.getUrl().then((uri) => uri.toString());
    }
  
    Future<void> loadUrl(String url) {
      if (_inAppWebViewController == null) {
        return Future.sync(() => null);
      }
      return _inAppWebViewController!
          .loadUrl(urlRequest: URLRequest(url: Uri.parse(url)));
    }
bfb40cd0   liangchengyou   feat:忘记密码获取验证码
78
79
80
81
  
    @override
    void initState() {
      super.initState();
c95453ce   Key   feat: User界面完善
82
      /*if (Platform.isIOS) {
bfb40cd0   liangchengyou   feat:忘记密码获取验证码
83
84
85
        LimitingDirectionCsx.setScreenDirection(DeviceDirectionMask.PortraitUpsideDown);
      } else {
        SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
c95453ce   Key   feat: User界面完善
86
      }*/
bfb40cd0   liangchengyou   feat:忘记密码获取验证码
87
  
4b858f67   吴启风   feat:webview库替换
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
      // _controller = WebViewController()
      //   ..setJavaScriptMode(JavaScriptMode.unrestricted)
      //   ..setBackgroundColor(const Color(0x00000000))
      //   ..setNavigationDelegate(
      //     NavigationDelegate(
      //       onProgress: (int progress) {
      //         // Update loading bar.
      //       },
      //       onPageStarted: (String url) {
      //         Log.d("$TAG onPageStarted $url");
      //         EasyLoading.show();
      //       },
      //       onPageFinished: (String url) {
      //         Log.d("$TAG onPageFinished $url");
      //         EasyLoading.dismiss();
      //       },
      //       onWebResourceError: (WebResourceError error) {
      //         Log.d("$TAG onWebResourceError ${error.description}");
      //         EasyLoading.showError(error.description);
      //       },
      //       onUrlChange: (UrlChange change) {
      //         Log.d("$TAG onUrlChange ${change.url}");
      //       },
      //       onNavigationRequest: (NavigationRequest request) async {
      //         var url = request.url;
      //         Log.d("$TAG onNavigationRequest $url");
      //
      //         /// Allow the navigation
      //         // return NavigationDecision.navigate;
      //         /// Block the navigation
      //         /// return NavigationDecision.prevent;
      //         if (url.startsWith("alipay:") || url.startsWith("alipays")) {
      //           Log.d("$TAG onNavigationRequest 支付宝 $url");
      //           launch(request.url);
      //           return NavigationDecision.navigate;
      //         }
      //         if (url.startsWith('http:') || url.startsWith('https:')) {
      //           return NavigationDecision.navigate;
      //         } else {
      //           try {
      //             await launch(url);
      //           } catch (e) {
      //             print('Could not launch $request.url: $e');
      //           }
      //           return NavigationDecision.prevent;
      //         }
      //       },
      //     ),
      //   )
      //   ..loadRequest(Uri.parse(widget.urlStr));
bfb40cd0   liangchengyou   feat:忘记密码获取验证码
138
139
140
141
    }
  
    @override
    Widget build(BuildContext context) {
4b858f67   吴启风   feat:webview库替换
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
      return WillPopScope(
        onWillPop: () {
          Future<bool> canGoBack = _inAppWebViewController!.canGoBack();
          return canGoBack.then((isCanGoBack) {
            if (isCanGoBack) {
              _inAppWebViewController!.goBack();
              return false;
            } else {
              return true;
            }
          });
        },
        // return PopScope(
        //   canPop: () async {
        //     if (_controller != null) {
        //       bool canGoBack = await _controller!.canGoBack();
        //       return !canGoBack;
        //     }
        //     return true;
        //   },
        //   onPopInvoked: (PopDisposition disposition) async {
        //     if (_controller != null) {
        //       bool canGoBack = await _controller!.canGoBack();
        //       if (canGoBack) {
        //         _controller!.goBack();
        //         return PopDisposition.popCancelled;
        //       }
        //     }
        //     return PopDisposition.pop;
        //   },
        child: Scaffold(
            backgroundColor: Colors.red,
            appBar: WEAppBar(
              titleText: widget.webViewTitle,
              leadingWidth: 96,
              leading: Row(
                children: <Widget>[
                  IconButton(
                    icon: Image.asset(
                      'back_around'.assetPng,
                      height: 40.h,
                      width: 40.w,
                    ),
                    onPressed: () {
                      if (isCanGoBack) {
                        _inAppWebViewController!.goBack();
                      } else {
                        Navigator.pop(context);
                      }
                    },
                  ),
                  Visibility(
                    visible: isCanGoBack,
                    child: IconButton(
                      // icon: Image.asset(
                      //   'back_around'.assetPng,
                      //   height: 40.h,
                      //   width: 40.w,
                      // ),
                      icon: Icon(Icons.close),
                      onPressed: () {
                        Navigator.pop(context);
                      },
                    ),
                  ),
                ],
              ),
            ),
            body: Container(
              color: Colors.white,
              // child: SafeArea(
              child: InAppWebView(
                key: webViewKey,
                initialUrlRequest: URLRequest(
                  url: Uri.parse(widget.urlStr),
                ),
                initialUserScripts: UnmodifiableListView<UserScript>([]),
                initialOptions: webViewSettings,
                onWebViewCreated: (controller) {
                  _inAppWebViewController = controller;
                },
                onTitleChanged:
                    (InAppWebViewController controller, String? title) {
                  Log.d("$TAG onTitleChanged title=$title`");
                  setState(() {
                    if (title?.endsWith(".com") == true) {
                      widget.webViewTitle = defaultWebViewTitle;
                    } else {
                      widget.webViewTitle = title ?? defaultWebViewTitle;
                    }
                  });
                },
                shouldOverrideUrlLoading: (controller, navigationAction) async {
                  var url = navigationAction.request.url;
                  Log.d(
                      "$TAG shouldOverrideUrlLoading url=$url scheme=${url?.scheme}");
                  if (![
                    "http",
                    "https",
                    "file",
                    "chrome",
                    "data",
                    "javascript",
                    "about",
                  ].contains(url?.scheme ?? "")) {
                    Log.d("$TAG canLaunchUrl(url)=${canLaunchUrl(url!)}");
                    await canLaunchUrl(url)
                        ? await launchUrl(url)
                        : Log.e("对不起,打不开链接地址:$url");
                    return NavigationActionPolicy.CANCEL;
                  }
                  return NavigationActionPolicy.ALLOW;
                },
                onLoadStop: (controller, url) async {
                  Log.d("$TAG onLoadStop url=$url");
                  //页面加载完毕,显示隐藏AppBar的返回键
                  _inAppWebViewController!.canGoBack().then((canGoBack) => {
                        setState(() {
                          isCanGoBack = canGoBack;
                        })
                      });
                  _inAppWebViewController!.canGoForward().then((canForward) => {
                        setState(() {
                          isCanForward = canForward;
                        })
                      });
                },
                onLoadError: (controller, request, code, message) {
                  Log.d(
                      "$TAG onReceivedError request=$request error=$code message=$message");
                },
                onLoadHttpError: (controller, request, errorResponse, message) {
                  Log.d(
                      "$TAG onReceivedError request=$request errorResponse=$errorResponse message=$message");
                },
                onProgressChanged: (controller, progress) {
                  Log.d("$TAG onProgressChanged progress=$progress");
                  //进度从0 ~ 100
                  setState(() {
                    _progress = progress / 100.0;
                  });
                },
                onUpdateVisitedHistory: (controller, url, androidIsReload) {
                  Log.d("$TAG onUpdateVisitedHistory url=$url");
                },
                // onLoadResourceWithCustomScheme: (controller, request) {
                //   Log.d("$TAG onLoadResourceWithCustomScheme request=$request");
                // },
                onConsoleMessage: (controller, consoleMessage) {
                  // Log.d("$TAG onConsoleMessage consoleMessage=$consoleMessage");
                },
              ),
            )),
        // ),
bfb40cd0   liangchengyou   feat:忘记密码获取验证码
296
297
      );
    }
c95453ce   Key   feat: User界面完善
298
  }