英文:
Why is IconButton a stateless widget in Flutter, rather than being a stateful widget?
问题
在Flutter文档中,它说明:
> "一个无状态小部件永远不会改变。Icon、IconButton和Text是无状态小部件的示例。无状态小部件是StatelessWidget的子类。
>
> 一个有状态小部件是动态的:例如,它可以在用户交互或接收数据触发的事件的响应下改变其外观。Checkbox、Radio、Slider、InkWell、Form和TextField是有状态小部件的示例。有状态小部件是StatefulWidget的子类。"
这对我来说有些困惑,因为一个IconButton可以在用户交互触发的事件下改变其外观。在这个例子中,我不理解无状态和有状态之间的区别。
当创建自定义小部件时,我不确定何时将其设置为有状态或无状态。
英文:
In the flutter documentation, it states
> "A stateless widget never changes. Icon, IconButton, and Text are examples of stateless widgets. Stateless widgets subclass StatelessWidget.
>
> A stateful widget is dynamic: for example, it can change its appearance in response to events triggered by user interactions or when it receives data. Checkbox, Radio, Slider, InkWell, Form, and TextField are examples of stateful widgets. Stateful widgets subclass StatefulWidget."
This is confusing to me, because an IconButton can change its appearance in response to events triggered by user interactions. I am not understanding the distinction between stateless and stateful given this example
when making a custom widget, I am unsure when to make it stateful or stateless
答案1
得分: 2
IconButton
可能是无状态的,但它使用了有状态的小部件(在这种情况下是ButtonStyleButton
)。状态由ButtonStyleButton
保存,而IconButton
仅是其周围的包装器,以使其更容易使用、设置默认值或使用正确的主题。
> 当制作自定义小部件时,我不确定何时将其设置为有状态或无状态。
如果可以的话,始终选择StatelessWidget
。只有在需要在状态中保存一些内容(并使用setState
)或StatefulWidget
的其他方法(例如initState
)时才需要StatefulWidget
。例如,您可以使用initState
在挂载小部件时仅触发一次对API的HTTP调用。
英文:
IconButton
might be stateless but it uses widgets that are stateful (ButtonStyleButton
in this case). The state is held by ButtonStyleButton
and IconButton
is only a wrapper around it to make it easier to use, set default values or use the correct theme.
> when making a custom widget, I am unsure when to make it stateful or stateless
Always go for a StatelessWidget
if you can. You only need StatefulWidget
if you need to save something in the state (and use setState
) or any other method of the StatefulWidget
like initState
for example. You could use initState
to trigger an http call to an API only once when the widget is mounted for example.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论