Flutter:无状态小部件中的可变字段 [英] Flutter: Mutable fields in stateless widgets

查看:132
本文介绍了Flutter:无状态小部件中的可变字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

StatelessWidget被标记为immutable.但是,我使用的是scoped model,这意味着我避免使用StatefulWidget并使用model来更改StatelessWidget中的state.这导致我在StatelessWidget中具有non-final fields,这不会引起errors,因为它只是一个warning.但是我想知道是否有更好的方法?

The class StatelessWidget is marked as immutable. However, I am using the scoped model, which means that I avoid StatefulWidget and use the model to alter state in StatelessWidget. This leads to me having non-final fields in StatelessWidget, which doesn't cause errors, because it's just a warning. But I wondered if there is a better way?

推荐答案

无状态窗口小部件应仅具有最终字段,且没有例外.原因:当父窗口小部件由于某种原因(屏幕旋转,动画,滚动...)而重建时,将调用父窗口的build方法,这将导致所有窗口小部件都被重建.

Stateless widgets should only have final fields, with no exceptions. Reason: When the parent widget is rebuilt for some reason (screen rotation, animations, scrolling...), the build method of the parent is called, which causes all widgets to be reconstructed.

对扩展StatefulWidget进行分类必须遵循相同的规则,因为它们也被重构.在布局树的窗口小部件生命周期中,仅保留可以包含可变字段的State.

Classes the extend StatefulWidget must follow the same rule, because those are also reconstructed. Only the State, which can contain mutable fields, is kept during the lifetime of widget in the layout tree.

没有理由避免使用StatefulWidget.这是Flutter的基本构建块.

There is no reason to avoid StatefulWidget. It is a fundamental building block of Flutter.

实际上,ScopedModelDescendant也是有状态的小部件. scoped_model的主要好处是您可以将业务逻辑与小部件层分开.它并不能消除对有状态小部件的需求.

In fact, ScopedModelDescendant is also a stateful widget. The primary benefit of scoped_model is that you can separate the business logic from the widget layer. It doesn't eliminate the need for stateful widgets.

将有状态小部件用于:

  • 将作用域模型注入树(用于构建ScopedModel小部件的小部件).将Model实例存储在State中.
  • 存储用户输入(TextEditingController,复选框的状态)
  • 需要AnimationController s
  • 的动画小部件
  • 要存储以Controller(TabControllerScrollController,...)结尾的任何内容
  • Injecting scoped models into the tree (the widget that builds the ScopedModel widget). Store the Model instance in the State.
  • Storing user input (TextEditingController, state of a checkbox)
  • Animated widgets which require AnimationControllers
  • To store anything that ends with Controller (TabController, ScrollController, ...)

使页面"小部件(构建Scaffold的小部件,可使用Navigator访问)是有状态的,这通常是一个好主意.通常,这些是作用域模型的宿主.

It is often a good idea to make the "page" widgets (widgets which build a Scaffold, accessible using the Navigator) stateful. Often these are the hosts for scoped models.

这篇关于Flutter:无状态小部件中的可变字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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