在StatelessWidget的类注释中有一条优化建议是:
Use
const
widgets where possible, and provide aconst
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 (...) {
...
}