flutter StatefulWidget 和StatelessWidget(四)

1 StatelessWidget

创建之后,状态不可改变。如显示的文本等。具体类型如Text,Button,Icon等都继承自StatelessWidget。

2 StatefulWidget

创建之后,其状态可能会发生改变。如显示的文本、勾选状态等。典型的如Image、Checkbox等继承自StatefulWidget。状态的更新,在调用setState后激发。

附上对比图:

关于使用的官方原文:

How do I decide when to use a StatefulWidget?

If the visuals of the widget only change depending on the parent widget and all of its state is defined in the constructor, use a StatelessWidget.

If there is an internal state (that could e. g. be a text color) that changes independent from the parent (e. g. a color changes when you tap it), use a StatefulWidget.

If you are in doubt, start with a StatelessWidget. Once you realize you’re approaching its boundaries, you can easily switch to a StatefulWidget by using your IDEs shortcuts.

简单理解如下,当widget是依赖父widget改变才发生改变的时候,定义为statelessWidget。

如果状态由自身决定的时候,使用statefullWidget。 

Does a StatelessWidget become stateful when it contains a StatefulWidget?

If you look at it on a more abstract level, you can say so. But in the world of Flutter where stateful and stateless are predefined terms it does not. The parent has no knowledge or responsibility of the child’s state. The stateful child manages its state on its own.

 从代码继承的角度看,stateless会自动变成statefull。但从flutter布局的角度看(预先定义好类型),不是,因为父widget不知道子widget的状态。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值