Flutter 第一次打开webView视图时界面有卡顿的感觉,

2023-04-16  本文已影响0人  hylccmh

问题描述:
在APP中第一次打开一个webview视图的时候,明显的可以感觉到界面会有卡顿的感觉,同时pop到上一个界面时,界面会闪烁。

关于第一个问题,是由于 dart 语言是单线程 任务处理,当我们push一个 webview视图时,界面要做动画 和 webview 加载 URL 资源任务,存在资源抢夺的情况,视觉表现就是 感觉动画不流畅,这里给出的解决方案是优先处理 push,等动画加载完成,在加载 webview 内容。

关于第二问题,具体的原因还不清楚,但是,这里给出的解决方案是,在webview视图 pop 之前,把webview 组件给移除,返回到上一个界面时,就没有了闪烁。
具体代码如下:

class FDWebViewContainer extends StatefulWidget {

  late String url; /// 网址
  final String? title; ///标题

  FDWebViewContainer({super.key,required this.url,this.title});

  @override
  FDWebViewContainerState createState() => FDWebViewContainerState();
}

class FDWebViewContainerState extends State<FDWebViewContainer> {
  final webViewKey = UniqueKey();
  InAppWebViewController? _webViewController;
  double _progress = 0;    ///进度条

  ///由于webView首次初始化会有卡顿的感觉,所以要等 push 动画结束后再加载 webview
  bool _animationCompleted = false;

  @override
  Widget build(BuildContext context) {
    var route = ModalRoute.of(context);
    if (route != null && !_animationCompleted) {
      void handler(status) {
        if (status == AnimationStatus.completed) {
          route.animation?.removeStatusListener(handler);
          setState(() {
            _animationCompleted = true;
          });
        }
      }
      route.animation?.addStatusListener(handler);
    }
    return  MaterialApp(
      home: Scaffold(
        appBar:  FDAppBar(title: widget.title,leftCallback: (){
          /// 适配 Android 设备 返回 页面闪烁的问题
          setState(() {
            _animationCompleted = false;
          });
          Navigator.of(context).pop('');
        },
      ),
      body: !_animationCompleted? Container(
        decoration: const BoxDecoration(
          color: Colors.white,
        ),
      ) : SafeArea(
        child: Column (
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            ///加载进度条
            Container(
              padding:const EdgeInsets.only(left: 0,right: 0,top: 0,bottom: 0),
              height: 2,
              child: _progress < 1.0 ? LinearProgressIndicator(
                value: _progress,
                valueColor: const AlwaysStoppedAnimation(Colors.green),
                backgroundColor: Colors.grey[200],
              ) : Container(),
            ),
            Expanded(
              child: InAppWebView(
                initialUrlRequest: URLRequest(url: Uri.parse(widget.url)),
                initialOptions: FDWebViewConfig.config(),

                /// 获取 WebViewController 对象,可以在此处实现 js 通讯
                onWebViewCreated: (InAppWebViewController controller){
                  _webViewController = controller;

                },
                ///开始加载
                onLoadStart: (InAppWebViewController controller,Uri? url){

                },
                ///加载结束
                onLoadStop: (InAppWebViewController controller, Uri? url) async {


                },
                ///加载失败
                onLoadError: (InAppWebViewController controller, Uri? url, int code,
                    String message) {

                },
                /// http 请求出错
                onLoadHttpError: (InAppWebViewController controller, Uri? url,
                    int statusCode, String description) {

                },
                ///加载进度
                onProgressChanged: (InAppWebViewController controller, int progress) {
                  // print(" onProgressChanged progress:$progress");
                  setState(() {
                    _progress = progress / 100.0;
                  });
                },

                shouldOverrideUrlLoading: (InAppWebViewController controller,
                    NavigationAction navigationAction) async {
                  // print("shouldOverrideUrlLoading navigationAction:$navigationAction");
                  return null;
                },
                /// 资源加载监听器
                onLoadResource:(InAppWebViewController controller, LoadedResource resource) {
                  // print("onLoadResource resource:$resource");
                },
                /// 滚动监听器
                onScrollChanged: (InAppWebViewController controller, int x, int y) {
                  // print(" onScrollChanged x:$x  y:$y");
                },
                onLoadResourceCustomScheme:(InAppWebViewController controller, Uri url) async {
                  // print(" onLoadResourceCustomScheme url:$url");
                  return null;
                },
                onCreateWindow: (InAppWebViewController controller,
                    CreateWindowAction createWindowAction) async {
                  // print(" onCreateWindow");
                  return true;
                },
                onCloseWindow: (InAppWebViewController controller) {
                  // print(" onCloseWindow");
                },
                /// 过量滚动监听器
                onOverScrolled: (InAppWebViewController controller, int x, int y,
                    bool clampedX, bool clampedY) async {
                  // print(" onOverScrolled x:$x  y:$y clampedX:$clampedX clampedY:$clampedY");
                },

                ///Android特有功能,请求加载链接,可以拦截资源加载,并替换为本地Web离线包内的资源
                androidShouldInterceptRequest: (InAppWebViewController controller,
                    WebResourceRequest request) async {
                  print(" androidShouldInterceptRequest request:$request");
                  return null;
                },

                ///iOS特有功能
                iosOnNavigationResponse: (InAppWebViewController controller,
                    IOSWKNavigationResponse navigationResponse) async {
                  return null;
                },
              ),
              ),
          ],
        ),
      ),
      ),
    );
  }
}
上一篇 下一篇

猜你喜欢

热点阅读