[英]Flutter: When to create Stateless or Stateful page?
I am new to Flutter.我是 Flutter 的新手。 Everything in Flutter is a widget, and there are two types of widgets, which are Stateless and Stateful.
Flutter 中的一切都是一个小部件,有两种类型的小部件,即 Stateless 和 Stateful。 Understood that stateless widgets are widgets that will not change or user can't interact with (texts, icons, etc) while stateful widgets are widgets that will change its state for example because of user interactions.
理解无状态小部件是不会改变或用户无法与之交互(文本、图标等)的小部件,而有状态小部件是会因用户交互而改变其状态的小部件。
When we want to create a new custom page we usually extends the page from StatelesWidget or StatefulWidget.当我们想要创建一个新的自定义页面时,我们通常从 StatelesWidget 或 StatefulWidget 扩展页面。 Since a StatelesWidget can have StatefulWidget as its children and vice-versa, then when should we extend a page as a StatefulWidget or as a StatelessWidget?
既然 StatelesWidget 可以有 StatefulWidget 作为它的孩子,反之亦然,那么我们什么时候应该将页面扩展为 StatefulWidget 或 StatelessWidget?
Thank you.谢谢你。
If the page itself has some kind of status, then it should be a stateful widget.如果页面本身有某种状态,那么它应该是一个有状态的小部件。 For example you want to load something remotely, and display a progress indicator while data is being fetched.
例如,您希望远程加载某些内容,并在获取数据时显示进度指示器。 When loading is complete, the state of the page is changed, and instead of the progress indicator you display whatever you want.
加载完成后,页面的状态会发生变化,而不是显示任何您想要的进度指示器。
But it is also possible that the page itself is a stateless widget, and has a child widget, a container for example, and this container is stateful, managing the above mentioned remote loading or depends on some kind of user interaction.但是也有可能页面本身是一个无状态的小部件,并且有一个子小部件,例如一个容器,这个容器是有状态的,管理上述远程加载或依赖于某种用户交互。
State management is a central issue in Flutter, you have many options, and it is not always easy to find the best.状态管理是 Flutter 的核心问题,您有很多选择,但要找到最好的并不总是那么容易。 You can easily get into fighting the framework instead of letting it to do the job for you.
您可以轻松地与框架进行斗争,而不是让它为您完成工作。 If you are new to this, I would suggest watching some videos, they helped me a lot, for example this or this .
如果您对此不熟悉,我建议您观看一些视频,它们对我帮助很大,例如this或this 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.