无状态小部件和有状态小部件之间有什么区别? [英] What difference between stateless and stateful widgets?

查看:104
本文介绍了无状态小部件和有状态小部件之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Dart/flutter,并试图了解Widgets系统的工作方式.但是我不明白无状态小部件和有状态小部件之间的区别是什么?例如我有按钮.它有什么类型?

I am learning Dart/flutter and trying to understand how Widgets system works. But I can't understand what difference between stateless and stateful widgets? For example I have button. What type it have?

让我们想象两种情况. 我将文本发送到按钮并显示它. 我将文本发送到按钮,它会更改颜色.

Let's imagine two cases. I send text to button and it's display it. I send text to button and it's change color.

如果我创建的窗口小部件类型不正确怎么办?

What will be if I will create not proper Widget type?

推荐答案

共有3种小部件,而不仅仅是2种.

There are 3 kind of widgets, not just 2.

  • 状态小部件
  • 无状态小工具
  • 继承的小部件

无状态小部件就像一个常量.这是一成不变的.如果要更改无状态小部件显示的内容,则必须创建一个新的小部件.

A stateless widget is like a constant. It is immutable. If you want to change what is displayed by a stateless widget, you'll have to create a new one.

有状态的小部件则相反.他们还活着,可以与用户互动.有状态的小部件可以访问名为setState的方法,该方法基本上对框架说:您好,我想显示其他内容.您可以重画我吗?".

Stateful widgets are the opposite. They are alive and can interact with the user. Stateful widgets have access to a method named setState, which basically says to the framework "Hello, I want to display something else. Can you redraw me please ?".

最后,继承的小部件是两个世界的混合体.它是不变的和无状态的.但是另一个小部件(无论它是什么)都可以订阅该继承的小部件. 这意味着当您用一个新部件替换继承的部件时,所有已订阅旧部件的部件都将被重绘.

Finally, Inherited widget is a mixt of both worlds. It is immutable and stateless. But another widget (whatever it is) can subscribe to that inherited widget. Which means that when you replace your inherited widget by a new one, all the widgets that has subscribed to the old one will be redrawn.

最后,通常将有状态窗口小部件用作控制器. 无状态小部件将像视图一样使用. 继承的小部件将是您的配置文件或模型.

In the end, a stateful widget will usually be used like a Controller. A stateless widget will be used like a View. And the inherited widget will be your configuration file or your Model.

这篇关于无状态小部件和有状态小部件之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆