Blame view

lib/common/pages/wow_web_page.dart 10.9 KB
1e868ad2   吴启风   feat:webview库替换
1
2
  import 'dart:collection';
  
bfb40cd0   liangchengyou   feat:忘记密码获取验证码
3
  import 'package:flutter/material.dart';
1e868ad2   吴启风   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';
  
1e868ad2   吴启风   feat:webview库替换
10
11
12
  import '../../utils/log_util.dart';
  import '../../utils/toast_util.dart';
  
bfb40cd0   liangchengyou   feat:忘记密码获取验证码
13
  class WowWebViewPage extends StatefulWidget {
1e868ad2   吴启风   feat:webview库替换
14
15
    WowWebViewPage(
        {super.key, required this.urlStr, required this.webViewTitle});
bfb40cd0   liangchengyou   feat:忘记密码获取验证码
16
17
  
    final String urlStr;
1e868ad2   吴启风   feat:webview库替换
18
    String webViewTitle;
bfb40cd0   liangchengyou   feat:忘记密码获取验证码
19
20
21
22
23
24
25
  
    @override
    State<StatefulWidget> createState() {
      return _WowWebViewPageState();
    }
  }
  
1e868ad2   吴启风   feat:webview库替换
26
27
28
29
30
31
32
33
34
  /// 生成进度条组件,进度从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:忘记密码获取验证码
35
  class _WowWebViewPageState extends State<WowWebViewPage> {
1e868ad2   吴启风   feat:webview库替换
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
    late InAppWebViewController? _inAppWebViewController;
    final GlobalKey webViewKey = GlobalKey();
    double _progress = 0;
    bool isCanGoBack = false;
    bool isCanForward = false;
    late final String defaultWebViewTitle = widget.webViewTitle;
  
    // 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,
      ),
    );
bfb40cd0   liangchengyou   feat:忘记密码获取验证码
64
  
1e868ad2   吴启风   feat:webview库替换
65
66
67
68
69
70
71
72
73
74
75
76
77
78
    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:忘记密码获取验证码
79
80
81
82
  
    @override
    void initState() {
      super.initState();
c95453ce   Key   feat: User界面完善
83
      /*if (Platform.isIOS) {
bfb40cd0   liangchengyou   feat:忘记密码获取验证码
84
85
86
        LimitingDirectionCsx.setScreenDirection(DeviceDirectionMask.PortraitUpsideDown);
      } else {
        SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
c95453ce   Key   feat: User界面完善
87
      }*/
bfb40cd0   liangchengyou   feat:忘记密码获取验证码
88
  
1e868ad2   吴启风   feat:webview库替换
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
138
      // _controller = WebViewController()
      //   ..setJavaScriptMode(JavaScriptMode.unrestricted)
      //   ..setBackgroundColor(const Color(0x00000000))
      //   ..setNavigationDelegate(
      //     NavigationDelegate(
      //       onProgress: (int progress) {
      //         // Update loading bar.
      //       },
      //       onPageStarted: (String url) {
      //         Log.d("WQF onPageStarted $url");
      //         EasyLoading.show();
      //       },
      //       onPageFinished: (String url) {
      //         Log.d("WQF onPageFinished $url");
      //         EasyLoading.dismiss();
      //       },
      //       onWebResourceError: (WebResourceError error) {
      //         Log.d("WQF onWebResourceError ${error.description}");
      //         EasyLoading.showError(error.description);
      //       },
      //       onUrlChange: (UrlChange change) {
      //         Log.d("WQF onUrlChange ${change.url}");
      //       },
      //       onNavigationRequest: (NavigationRequest request) async {
      //         var url = request.url;
      //         Log.d("WQF onNavigationRequest $url");
      //
      //         /// Allow the navigation
      //         // return NavigationDecision.navigate;
      //         /// Block the navigation
      //         /// return NavigationDecision.prevent;
      //         if (url.startsWith("alipay:") || url.startsWith("alipays")) {
      //           Log.d("WQF 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:忘记密码获取验证码
139
140
141
142
    }
  
    @override
    Widget build(BuildContext context) {
1e868ad2   吴启风   feat:webview库替换
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
296
297
298
299
      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(
                            "WQF 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(
                        "WQF shouldOverrideUrlLoading url=$url scheme=${url?.scheme}");
                    if (![
                      "http",
                      "https",
                      "file",
                      "chrome",
                      "data",
                      "javascript",
                      "about",
                    ].contains(url?.scheme ?? "")) {
                      Log.d(
                          "WQF shouldOverrideUrlLoading contains scheme=${url?.scheme} uri=${url?.data?.uri} url=$url");
                      Log.d("WQF canLaunchUrl(url)=${canLaunchUrl(url!)}");
                      await canLaunchUrl(url)
                          ? await launchUrl(url)
                          : showToast("对不起,打不开链接地址:$url");
                      return NavigationActionPolicy.CANCEL;
                    }
                    return NavigationActionPolicy.ALLOW;
                  },
                  onLoadStop: (controller, url) async {
                    Log.d("WQF 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(
                        "WQF onReceivedError request=$request error=$code message=$message");
                  },
                  onLoadHttpError: (controller, request, errorResponse, message) {
                    Log.d(
                        "WQF onReceivedError request=$request errorResponse=$errorResponse message=$message");
                  },
                  onProgressChanged: (controller, progress) {
                    Log.d("WQF onProgressChanged progress=$progress");
                    //进度从0 ~ 100
                    setState(() {
                      _progress = progress / 100.0;
                    });
                  },
                  onUpdateVisitedHistory: (controller, url, androidIsReload) {
                    Log.d("WQF onUpdateVisitedHistory url=$url");
                  },
                  // onLoadResourceWithCustomScheme: (controller, request) {
                  //   Log.d("WQF onLoadResourceWithCustomScheme request=$request");
                  // },
                  onConsoleMessage: (controller, consoleMessage) {
                    // Log.d("WQF onConsoleMessage consoleMessage=$consoleMessage");
                  },
                ),
              )),
        // ),
bfb40cd0   liangchengyou   feat:忘记密码获取验证码
300
301
      );
    }
c95453ce   Key   feat: User界面完善
302
  }