如何在SearchDelegate中使用setState [英] how to use setState in SearchDelegate
问题描述
我想通过添加带有一些单选按钮和其他小部件的表单来为搜索结果添加更多过滤器.该文档指出Radio
不保持状态,应调用父级的setState
onChange
方法来重建小部件.调用showModalBottomSheet
后将显示该表格.
观察search.dart
似乎只有在查询更改时才在内部调用setState
I want to add more filter on search result by adding a form with some radio buttons and other widgets. The doc states that Radio
does not keep state and should call parent's setState
onChange
method to rebuild widget. The form will be displayed after calling showModalBottomSheet
.
Looking at search.dart
looks like setState is called internally only on query changed
我做了什么
假设没有这样的方法setState
,我重新显示对话框,先调用Navigation.pop(context)
,再调用showModalBottomSheet
.现在,单选按钮可以更新onChanged的值,但是重新分配对话框的过渡看起来很丑(每次更改值时都会滑动动画).
what i did
assuming there was no such method, setState
, I redisplay dialogue, call Navigation.pop(context)
followed by showModalBottomSheet
. The radio buttons can now update the value onChanged but the transition to redislay the dialogue looks ugly (sliding animation every time the value changes).
是否可以在searchDelegate中使用setState?如何使用?
Is it possible to use setState in searchDelegate and how?
推荐答案
您需要使用的是StatefulBuilder
,由showModalBottomSheet
的构建器返回.
What you need to use is StatefulBuilder
, returned by showModalBottomSheet
's builder.
StatefulBuilder
提供了setState
方法来重建其自己的子树.
StatefulBuilder
provides setState
method to rebuild its own subtree.
例如
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");
});
在我的示例中,模态内容的setState
被声明为modalSetState
builder参数.
In my example setState
for the content of the modal is declared as modalSetState
builder argument.
这篇关于如何在SearchDelegate中使用setState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!