Flutter: Mutable fields in stateless widgets

↘锁芯ラ 提交于 2020-05-29 08:25:57

问题


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?


回答1:


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.

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.

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

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.

Use stateful widgets for:

  • 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, ...)

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.



来源:https://stackoverflow.com/questions/53192469/flutter-mutable-fields-in-stateless-widgets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!