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的状态。