我想通过添加带有一些单选按钮和其他小部件的表单来为搜索结果添加更多过滤器。该文档指出Radio不保持状态,应该调用父级的setState onChange方法来重建小部件。调用后将显示该表单showModalBottomSheet。看着search.dart貌似的setState在内部调用仅在查询变化
我所做的
假设没有这样的方法setState,我重新显示对话,Navigation.pop(context)然后调用showModalBottomSheet. 单选按钮现在可以更新 onChanged 值,但重新显示对话的过渡看起来很难看(每次值更改时滑动动画)。
是否可以在 searchDelegate 中使用 setState 以及如何使用?
小智 8
@George 已经提供了解决方案,但这里有一个使用 SearchDelegate 时的完整示例:
class DataSearch extends SearchDelegate<String> {
bool _isItemSelected = true;
//...rest of the @override methods
@override
Widget buildSuggestions(BuildContext context) {
return StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return CheckboxListTile(
title: const Text('Item'),
value: _isItemSelected,
onChanged: (bool newValue) {
setState(() {
_isItemSelected = newValue;
});
},
);
});
}
}
Run Code Online (Sandbox Code Playgroud)
您需要使用的是StatefulBuilder,由showModalBottomSheet的构建者返回。
StatefulBuilder提供setState重建自己的子树的方法。
例如
int selected;
showModalBottomSheet(context: context, builder: (_) =>
StatefulBuilder(builder: (modalContext, modalSetState) =>
Column(children: <Widget>[
Text("Select radio button"),
RadioListTile(
value: 1,
groupValue: selected,
onChanged: (val) => modalSetState(() => selected = val),
title: Text("One")
),
RadioListTile(
value: 2,
groupValue: selected,
onChanged: (val) => modalSetState(() => selected = val),
title: Text("Two")
),
])
)
).whenComplete(() {
print("Selected: $selected");
});
Run Code Online (Sandbox Code Playgroud)
在我的示例中,setState模式的内容被声明为modalSetState构建器参数。
| 归档时间: |
|
| 查看次数: |
2219 次 |
| 最近记录: |