flutter渲染优化之const

在StatelessWidget的类注释中有一条优化建议是:

Use const widgets where possible, and provide a const constructor for the widget so that users of the widget can also do so.

也就是用const定义StatelessWidget的构造,使用这个widget的地方才有可能使用const。

例子

在官方的计数器demo中,可以使用const定义固定文本的Text,对比添加前后的区别也很明显,Text没有重新渲染。

原理:

它的原理很简单在每次element树刷新到方法updateChild时,有一个case是判断element对应的widget和新widget如果相等,那么不会更新当前节点。
当我们用const定义的widget,且参数一致时,就会进入这个case。

if (hasSameSuperclass && child.widget == newWidget) {
        if (child.slot != newSlot)
          updateSlotForChild(child, newSlot);
        newChild = child;
} else if (...) {
	...
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值