Flutter性能揭秘之RepaintBoundary

318 篇文章 18 订阅
9 篇文章 0 订阅

作者: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);

  @override
  void 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)
      );
    }
  }

  @override
  bool 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);

  @override
  void paint(Canvas canvas, Size size) {
    canvas.drawCircle(
      _offset,
      10.0,
      new Paint()..color = Colors.green,
    );
  }

  @override
  bool 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 {

  @override
  State 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(),
        ),
      ),
    );
  }

  @override
  Widget 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值