当前位置:网站首页>关于 StatefulWidget,你不得不知道的原理和要点!
关于 StatefulWidget,你不得不知道的原理和要点!
2022-07-26 22:14:00 【InfoQ】
前言
StatelessWidgetStatefulWidgetsetStateStatefulWidgetStatefulWidget 的分类
StatefulWidgetsetStateStatefulWidgetinitStateStatefulWidgetsetStatesetStateStatefulWidget 的渲染机制
RenderObjectStatefulWidgetsetStateclass ItemCounter extends StatefulWidget {
ItemCounter({Key? key, required this.name}) : super(key: key);
final String name;
@override
_ItemCounterState createState() => _ItemCounterState();
}
class _ItemCounterState extends State<ItemCounter> {
int count = 0;
@override
Widget build(BuildContext context) {
return GestureDetector(
child: Text('${widget.name}: $count'),
onTap: () {
setState(() {
count++;
});
},
);
}
}
StatefulElementStatefulElement(StatefulWidget widget)
: state = widget.createState(),
//...
StatefulElementStatelessElementText(Tom:0)GestureDetectorStatecount
countcountbuildText(Tom: 1)WidgetText(Tom:0)WidgetTreeText(Tom: 1)WidgetWidgetStatefulElementWidgetStatefulElement

WidgetStatefulElementStatefulElementWidgetItemCounter(name: 'Tom')ItemCounter (name: 'Dan')



didUpdateWidget@override
void didUpdateWidget(covariant ItemCounter oldWidget) {
super.didUpdateWidget(oldWidget);
}
StatefulWidget 使用注意事项
setStateStatefulWidget- 尽可能将组件树的状态维护往下推到叶子节点。这个很好理解,状态维护层级越高,意味着重建的组件树越大。当然是将状态维护放在低层级的叶子节点性能更高。举个例子,假设你页面中有一个每秒定时更新的时钟组件,那么这个时间状态的维护应该单独抽出一个时钟组件,由它自己维护时间状态。
- 最小化
StatefulWidget的State中build方法构建的组件的数量。理想情况下,一个StatefulWidget应该只有一个子组件,且这个组件对应一个RenderObject。这个在现实中可能很难满足,但是这是一个指导原则,如果你的StatefulWidget的构建了太多组件,那么性能自然而然会下降。这个时候应该要考虑使用状态管理插件进行局部刷新了。
- 如果子组件树在整个生命周期都不改变的话,那么应该考虑将该子组件树缓存起来重复利用。这会比每次重新构建这个子组件树性能好很多。通常的做法是将这个子组件树单独抽离为一个
Widget,然后作为子组件传给StatefulWidget。
- 尽可能地使用
const修饰子组件构造方法。这个我们在讲const时(解密 Flutter 的 const 关键字)有介绍过。实际上,使用const修饰相当于是一种缓存方式。
- 尽可能避免更改子组件树的层级或子组件树中的组件类型。例如在返回子组件时,有可能会根据条件返回子组件或将子组件包裹在
IgnorePointer中。这种方式其实就是改变了子组件树的层级。应该将子组件统一包裹在IgnorePointer中,然后通过IgnorePointer的ignoring属性来控制。这是因为,任何更改子组件树深度的操作都会需要重新构建、重新布局、重新绘制整个子组件树。而只更改某个节点的属性的话,将会将改变的范围缩小很多(例如这个例子中,就不需要重新布局和重绘)。
- 假设不得不更改子组件树的层级,那么应该考虑将子组件树中不变的部分使用 GlobalKey 使得这部分在整个
StatefulWidget的生命周期都保持一致。如果不方便使用GlobalKey的话,那么可以考虑使用KeyedSubtree组件来应用GlobalKey。
- 如果
StatefulWidget中有些属性是不变的话,那么 这些属性的定义应该优先放在Widget的定义中,并声明为final,而不是State中,这样可以减少State需要维护的数据。
总结
- 如果时间允许,一开始就多看看官方文档、相关周边的应用及说明文档,这样会减少后续很多的开发成本和时间——尤其是遇到性能瓶颈需要重构的时候。
- 如果时间不允许,那么遇到问题的时候不要盲目折腾,回到官方文档先看几遍,Flutter 的官方文档非常详尽,而且还配套了很多讲解视频,能够解决你大部分困惑。
- 多输入,虽然国内 Flutter 的玩家不太多,但是国外的话还是很多的,坚持逛逛国外的博客,官网说明,能够让你少走很多弯路。
边栏推荐
- 2022 latest Tibet Construction Safety Officer simulation question bank and answers
- Leetcode:857. Minimum cost of employing K workers [think in blocks + start with simplicity]
- Which is better, caiqian school or qiniu school? Is it safe
- Day07 MySQL knowledge points re summary and multi table query
- Module 8 (message queue MySQL table storing message data)
- MySQL summarizes common scenarios of MySQL index failure
- Reduce power consumption and upgrade functions! Qiyingtailun released the second generation voice AI chip: the module price is as low as 14.99 yuan!
- 纷享销客罗旭对话西门子王海滨:先进制造,要向数字化要效益
- Parameter analysis and stone jumping board
- Huawei atlas900 reveals the secret: it integrates thousands of shengteng 910 chips, and its computing power is comparable to 500000 PCs!
猜你喜欢

测试开发是开发吗?

SQL二次注入详解

利用Go制作微信机器人(一)发送消息

Counter attack dark horse: devdbops training, give you the best courses!

Apifox -- a better API testing tool than postman

json格式化小工具--pyqt5实例

Embedded SIG | 分布式软总线

Page file system based on C language
![[hcip] OSPF route calculation](/img/1c/ee9eee2e723b850c401f7cddda1b27.png)
[hcip] OSPF route calculation

Those environment configurations and plug-ins of idea
随机推荐
Database full stack Engineers (devdbops) have low down payment and high return, and pay after employment
基于信心上界蒙特卡洛搜索树(UCT)实现四子棋
sql多表查询的练习
Use ECs and OSS to set up personal network disk
The secret weapon of apple iphone11 series: U1 chip may usher in the era of ultra wideband
App information reconnaissance & night God simulator burp packet capture configuration
蔚来杯2022牛客暑期多校训练营2
[untitled]
数据库全栈工程师(DevDBOps)低首付、高回报,先就业后付款
[MySQL] - index principle and use
Restful interface specification
After closing the Suzhou plant, Omron Dongguan plant announced its dissolution, and more than 2000 people are facing unemployment!
PostgreSQL 与 Navicat:数据库行业的中坚力量
由若干QWidget实现日历文档
Reinforcement learning weekly 55: lb-sgd, msp-drl & robust reinforcement learning against
中兴通讯:5G基站在全球发货已超过5万个!
ZTE: more than 50000 5g base stations have been shipped worldwide!
Makefile related syntax summary (openc910)
7.27抢先看 | openEuler 志高远,开源汇智创未来-开放原子全球开源峰会欧拉分论坛最详细议程出炉
纷享销客罗旭对话西门子王海滨:先进制造,要向数字化要效益