当前位置: 首页 > news >正文

Flutter性能揭秘之RepaintBoundary

作者:xuyisheng

Flutter会在屏幕上绘制Widget。如果一个Widget的内容需要更新,那就只能重绘了。尽管如此,Flutter同样会重新绘制一些Widget,而这些Widget的内容仍有部分未被改变。这可能会影响应用程序的执行性能,有时影响会非常巨大。如果您正在寻找一种方法,来防止不必要的部分重绘,您可以考虑利用RepaintBoundary。

在这篇博客理,我们将探讨Flutter中的RepaintBoundary。我们将看到如何实现RepaintBoundary的演示程序以及如何在您的flutter应用程序中使用它。

RepaintBoundary

RepaintBoundary类是Null安全的。首先,你需要了解什么是Flutter中的RepaintBoundary。它是一个为它的Child设置不同的展示层级的Widget。这个Widget为它的Child设置了一个不同的展示层级,如果一个子树与它周围的部分相比,会在意想不到的短时间内重新绘制,Flutter建议你使用RepaintBoundary来进一步提高性能。

为什么需要使用RepaintBoundary呢。

Flutter Widget与RenderObjects有关。一个RenderObject有一个叫做paint的函数,它被用来执行绘画过程。尽管如此,无论相关组件的内容是否发生变化,都可以使用绘制方法。这是因为,如果其中一个RenderObjects被设定为dirty,Flutter可能会对类似Layer中的其他RenderObjects进行重新绘制。当一个RenderObject需要利用RenderObject.markNeedsPaint进行重绘的时候,它就会建议它最接近的前辈进行重绘。祖先也会对它的前辈做同样的事情,直到根RenderObject。当一个RenderObject的paint策略被启动时,它在类似层中的所有相关RenderObjects都将被重新paint。

而有时,当一个RenderObject应该被重绘时,类似层中的其他RenderObjects不应该被重绘,因为它们的绘制产物保持不变。因此,如果我们只是对某些RenderObjects进行重绘,那会更好。利用RepaintBoundary可以帮助我们在渲染树上限制markNeedsPaint的生成,在渲染树下限制paintChild的生成。

RepaintBoundary可以将先前的渲染对象与相关的渲染对象解耦。通过这种方式,只对内容发生变化的子树进行重绘是可行的。利用RepaintBoundary可以进一步提高应用程序的执行效率,特别是当不应该被重绘的子树需要大量的工作来重绘时。

我们将做一个简单的演示程序,背景是利用CustomPainter绘制的,有10000个椭圆。同时还有一个光标,在客户接触到屏幕的最后一个位置后移动。下面是没有RepaintBoundary的代码。

示例

在正文中,我们将创建一个Stack widget。在里面,我们将添加一个StackFit.expand,并添加两个部件:_buildBackground(),和_buildCursor()。我们将定义以下代码。

Stack(fit: StackFit.expand,children: <Widget>[_buildBackground(),_buildCursor(),],
),

_buildBackground() widget

在_buildBackground()小组件中。我们将返回CustomPaint() widget。在里面,我们将在绘画器上添加BackgroundColor类。我们将在下面定义。另外,我们将添加isComplex参数为true,这意味着是否提示这个图层的绘画应该被缓存,willChange是false意味着是否应该告诉光栅缓存,这个绘画在下一帧可能会改变。

Widget _buildBackground() {return CustomPaint(painter:  BackgroundColor(MediaQuery.of(context).size),isComplex: true,willChange: false,);
}

BackgroundColor class

我们将创建一个BackgroundColor来扩展CustomPainter。

import 'dart:math';
import 'package:flutter/material.dart';class BackgroundColor extends CustomPainter {static const List<Color> colors = [Colors.orange,Colors.purple,Colors.blue,Colors.green,Colors.purple,Colors.red,];Size _size;BackgroundColor(this._size);@overridevoid paint(Canvas canvas, Size size) {final Random rand = Random(12345);for (int i = 0; i < 10000; i++) {canvas.drawOval(Rect.fromCenter(center: Offset(rand.nextDouble() * _size.width - 100,rand.nextDouble() * _size.height,),width: rand.nextDouble() * rand.nextInt(150) + 200,height: rand.nextDouble() * rand.nextInt(150) + 200,),Paint()..color = colors[rand.nextInt(colors.length)].withOpacity(0.3));}}@overridebool shouldRepaint(BackgroundColor other) => false;
}

_buildCursor() widget

在这个Widget,我们将返回Listener Widget。我们将在onPointerDown/Move方法中添加_updateOffset()组件,并添加CustomPaint。在里面,我们将添加一个Key和CursorPointer类。我们将在下面定义。另外,我们将添加ConstrainedBox()。

Widget _buildCursor() {return Listener(onPointerDown: _updateOffset,onPointerMove: _updateOffset,child: CustomPaint(key: _paintKey,painter: CursorPointer(_offset),child: ConstrainedBox(constraints: BoxConstraints.expand(),),),);
}

CursorPointer class

我们将创建一个CursorPointer来扩展CustomPainter。

import 'package:flutter/material.dart';class CursorPointer extends CustomPainter {final Offset _offset;CursorPointer(this._offset);@overridevoid paint(Canvas canvas, Size size) {canvas.drawCircle(_offset,10.0,new Paint()..color = Colors.green,);}@overridebool shouldRepaint(CursorPointer old) => old._offset != _offset;
}

当我们运行应用程序时,我们应该得到下面屏幕的输出,如屏幕下的视频。如果你试图在屏幕上移动指针,应用程序将非常滞后,因为它重新绘制背景,需要昂贵的计算。

下面,我们将添加RepaintBoundary。解决上述问题的答案是将CustomPaint部件包装成RepaintBoundary的子Widget。

Widget _buildBackground() {return RepaintBoundary(child: CustomPaint(painter:  BackgroundColor(MediaQuery.of(context).size),isComplex: true,willChange: false,),);
}

当我们运行应用程序时,我们应该得到屏幕的输出,就像屏幕下面的视频一样。有了这个简单的改变,现在当Flutter重绘光标时,背景就不需要重绘了。应用程序应该不再是滞后的了。

整个代码如下所示。

import 'package:flutter/material.dart';
import 'package:flutter_repaint_boundary_demo/background_color.dart';
import 'package:flutter_repaint_boundary_demo/cursor_pointer.dart';class HomePage extends StatefulWidget {@overrideState createState() => new _HomePageState();
}class _HomePageState extends State<HomePage> {final GlobalKey _paintKey = new GlobalKey();Offset _offset = Offset.zero;Widget _buildBackground() {return RepaintBoundary(child: CustomPaint(painter:  BackgroundColor(MediaQuery.of(context).size),isComplex: true,willChange: false,),);}Widget _buildCursor() {return Listener(onPointerDown: _updateOffset,onPointerMove: _updateOffset,child: CustomPaint(key: _paintKey,painter: CursorPointer(_offset),child: ConstrainedBox(constraints: BoxConstraints.expand(),),),);}@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(automaticallyImplyLeading: false,backgroundColor: Colors.cyan,title: const Text('Flutter RepaintBoundary Demo'),),body: Stack(fit: StackFit.expand,children: <Widget>[_buildBackground(),_buildCursor(),],),);}_updateOffset(PointerEvent event) {RenderBox? referenceBox = _paintKey.currentContext?.findRenderObject() as RenderBox;Offset offset = referenceBox.globalToLocal(event.position);setState(() {_offset = offset;});}
}

总结

在文章中,我解释了Flutter中RepaintBoundary的基本结构;你可以根据你的选择来修改这个代码。这是我对RepaintBoundary On User Interaction的一个小的介绍,它在使用Flutter时是可行的。

Android 学习笔录

Android 性能优化篇:https://qr18.cn/FVlo89
Android 车载篇:https://qr18.cn/F05ZCM
Android 逆向安全学习笔记:https://qr18.cn/CQ5TcL
Android Framework底层原理篇:https://qr18.cn/AQpN4J
Android 音视频篇:https://qr18.cn/Ei3VPD
Jetpack全家桶篇(内含Compose):https://qr18.cn/A0gajp
Kotlin 篇:https://qr18.cn/CdjtAF
Gradle 篇:https://qr18.cn/DzrmMB
OkHttp 源码解析笔记:https://qr18.cn/Cw0pBD
Flutter 篇:https://qr18.cn/DIvKma
Android 八大知识体:https://qr18.cn/CyxarU
Android 核心笔记:https://qr21.cn/CaZQLo
Android 往年面试题锦:https://qr18.cn/CKV8OZ
2023年最新Android 面试题集:https://qr18.cn/CgxrRy
Android 车载开发岗位面试习题:https://qr18.cn/FTlyCJ
音视频面试题锦:https://qr18.cn/AcV6Ap

http://www.lryc.cn/news/136608.html

相关文章:

  • 29.Netty源码之服务端启动:创建EventLoopSelector流程
  • Kotllin实现ArrayList的基本功能
  • C++的初步介绍,以及C++与C的区别
  • JDK 核心jar之 rt.jar
  • el-form表单验证:只在点击保存时校验(包含select、checkbox、radio)
  • Golang基本语法(上)
  • jenkins使用
  • 多线程基础篇(包教包会)
  • Android/Java中,各种数据类型之间的互相转换,给出各种实例,附上中文注释
  • 机器学习知识点总结:什么是EM(最大期望值算法)
  • 漏洞挖掘和安全审计的技巧与策略
  • [SpringBoot3]Web服务
  • 构建系统自动化-autoreconf
  • Mysql之InnoDB和MyISAM的区别
  • Unity 之 Transform.Translate 实现局部坐标系中进行平移操作的方法
  • PostgreSQL Error: sorry, too many clients already
  • Vue2(路由)
  • 中介者模式-协调多个对象之间的交互
  • Python框架【自定义过滤器、自定义数据替换过滤器 、自定义时间过滤器、选择结构、选择练习、循环结构、循环练习、导入宏方式 】(三)
  • 红黑树遍历与Redis存储
  • 前端处理图片文件的方法
  • 「Java」《深入解析Java多线程编程利器:CompletableFuture》
  • Docker容器与虚拟化技术:容器运行时说明与比较
  • vue导出文件流获取附件名称并下载(在response.headers里解析filename导出)
  • ​山东省图书馆典藏《乡村振兴战略下传统村落文化旅游设计》鲁图中大许少辉博士八一新书
  • 2023-08-19力扣每日一题-水题/位运算解法
  • Hadoop学习:深入解析MapReduce的大数据魔力之数据压缩(四)
  • LRU淘汰策略执行过程
  • Kotlin 高阶函数详解
  • DL——week2