【发布时间】:2020-10-26 07:14:06
【问题描述】:
我有一个StatelessWidget,它使用ScopedModel 来存储其数据。该小部件基本上显示了一个复选框列表和一些按钮来保存复选框的状态。
现在我想跟踪用户是否更改了任何复选框,即自显示小部件以来选中/取消选中它们。所以我添加了这样的内容:
class MyCheckboxScreen extends StatelessWidget{
bool _hasBeenModified = false;
void _itemCheckedChange(bool checked, MyModel model){
_hasBeenModified = true;
// Code to change the model here
}
void _onCloseButton(){
if( _hasBeenModified ){
// Show a warning that there are modifications that will not be be saved
}
}
void _onSaveButton(Context context, MyModel model){
model.save();
Navigator.of(context).pop();
}
}
这似乎可行,但我的 StatelessWidget 现在包含它自己的状态。
该状态不用于更新 UI 和重绘任何内容,它仅用于检查按下“关闭”按钮时是否对任何复选框进行了修改。
StatelessWidget 拥有这种内部状态是否安全?或者这可能是一个问题?例如,widget 是否会意外重新创建,内部状态会丢失?
我觉得the documentation 不是很清楚,它只是说
对于可以动态变化的组合,例如由于具有内部时钟驱动状态,或者取决于某些系统状态,请考虑使用 StatefulWidget。
但这听起来好像只适用于影响 UI 并需要重建小部件的状态。
【问题讨论】:
标签: flutter flutter-widget flutter-state statelesswidget