Flutter性能揭秘之RepaintBoundary

news/2025/2/1 19:53:56/

作者: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.ppmy.cn/news/1055540.html

相关文章

kafka复习:(3)自定义序列化器和反序列化器

一、实体类定义&#xff1a; public class Company {private String name;private String address;public String getName() {return name;}public void setName(String name) {this.name name;}public String getAddress() {return address;}public void setAddress(String a…

手机NFC功能是什么?

手机NFC功能是什么&#xff1f; 随着智能手机的不断发展和普及&#xff0c;NFC(近场通讯)功能已经成为了我们生活中不可或缺的一部分。NFC是一种无线通信技术&#xff0c;可以让手机和其他设备之间进行快速的数据交换和支付操作。那么&#xff0c;手机NFC功能是什么&#xff1…

OpenEuler 23.03恢复python3

OpenEuler 23.03装好后&#xff0c;无脑又装了一下python 3.11 .发现yum dnf 都不能用了&#xff0c;提示&#xff1a; Traceback (most recent call last): File "/usr/bin/yum", line 61, in <module> from dnf.cli import main ModuleNotFoundError:…

PyTorch翻译官网教程-PROFILING YOUR PYTORCH MODULE

官网链接 Profiling your PyTorch Module — PyTorch Tutorials 2.0.1cu117 documentation 分析pytorch模块 PyTorch包含一个分析器API&#xff0c;用于识别代码中各种PyTorch操作的时间和内存成本。分析器可以很容易地集成到代码中&#xff0c;结果可以作为表格打印或以JSON…

『SEQ日志』在 .NET中快速集成轻量级的分布式日志平台

&#x1f4e3;读完这篇文章里你能收获到 如何在Docker中部署 SEQ&#xff1a;介绍了如何创建和运行 SEQ 容器&#xff0c;给出了详细的执行操作如何使用 NLog 接入 .NET Core 应用程序的日志&#xff1a;详细介绍了 NLog 和 NLog.Seq 来配置和记录日志的步骤日志记录示例&…

Anaconda虚拟环境跨系统迁移

旧设备运行代码 conda activate name conda env export > environment.yml注意&#xff1a;如果当前路径已经有了 environment.yml 文件&#xff0c;conda 会重写这个文件 新设备运行代码 # 将environment.yml 拷贝到新设备中conda env create -f environment.yml

mysql、oracle、sqlserver常见方法区分

整理了包括字符串与日期互转、字符串与数字互转、多行合并为一行、拼接字段等一些常用的函数&#xff0c;当然有些功能实现的方法不止一种&#xff0c;这里列举了部分常用的&#xff0c;后续会持续补充。 MySQLOracleSQL Server字符串转数字 CAST(123 as SIGNED) 或 CONVERT(12…

详细介绍线程池的使用原理、参数介绍、优点、常见构造方法、使用案例、模拟实现

前言 创建和销毁一个线程时&#xff0c;这点损耗是微不足道的&#xff0c;但是当需要频繁的创建和销毁多个线程时&#xff0c;这个成本是不可忽视的&#xff0c;于是就有大佬创建了线程池&#xff0c;借助线程池来减少其中的成本。 目录 前言 一、线程池的使用原理 二、线程…