我有一个DropDownButton,它为我的产品添加了类别。添加后的产品DropDownButton显示类别,我选择了。添加产品后,我想刷新或清除DropDownButton。最好显示提示文本。
代码:
child: StreamBuilder<List<Categories>>(
stream: categories,
builder: ((context, snapshot) {
if (!snapshot.hasData)
return CircularProgressIndicator();
return DropdownButton(
hint: Text('choose category'),
value: _currentCategory,
items: snapshot.data
.map((doc) => DropdownMenuItem(
child: Text(doc.categoryname),
value: doc,
))
.toList(),
onChanged: (selectedCategory) =>
setState(() {
_currentCategory = selectedCategory;
}),
);
})),
),
SizedBox(height: 15),
RaisedButton(
onPressed: () {
if (_formKeyProduct.currentState.validate()) {
ProductService().addProduct(
_nameproductController.text,
_priceproductController.text,
_currentCategory.categoryname.toString());
_formKeyProduct.currentState.reset();
_nameproductController.clear();
_priceproductController.clear();
}
},
child: Text('add product'),发布于 2020-02-26 15:20:40
因为您选择的值是_currentCategory,所以使用
setState(() {
_currentCategory = null;
}
)应该能起作用。
编辑:
我看到有人对此投了反对票。这个答案是基于颤振1.22.6。如果它对颤振2不起作用,那就是为什么。
发布于 2022-11-22 23:09:59
这是一个完整的小部件,包括一个重新设置下拉值的按钮。它基于提供程序包。小部件包括一个按钮以清除选择。
class MyDataDropDown extends StatelessWidget {
@override
Widget build(final BuildContext context) {
return Consumer<HomeModel>(
builder: (context, model, child) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
decoration: BoxDecoration(
color: Colors.white, borderRadius: BorderRadius.circular(10)),
child: Row(
children: [
Expanded(
child: DropdownButton<SearchMyData>(
isExpanded: true,
value: model.currentMyData,
onChanged: (final SearchMyData? newValue) {
model.setCurrentMyData(newValue);
},
items: model.data.map<DropdownMenuItem<SearchMyData>>((SearchMyData value) {
return DropdownMenuItem<SearchMyData>(
value: value,
child: Text(MyDataDataUtils.getMyDataLabelDropDown(value), overflow: TextOverflow.ellipsis),
);
}).toList(),
// add extra sugar..
hint: const Text("Pick a data"),
icon: const Icon(Icons.arrow_drop_down),
underline: const SizedBox(),
),
),
IconButton( // clear dropdown button
onPressed: () => model.setCurrentMyData(null),
icon: Icon(Icons.clear))
],
),
);
},
);
}
}提供者类
class HomeModel extends ChangeNotifier{
....
UnmodifiableListView<SearchTheme> get data => UnmodifiableListView([your data here]);
SearchMyData? _selectedMyData;
SearchMyData? get currentMyData => _selectedMyData;
setCurrentMyData(final SearchMyData? item) {
_selectedMyData = item;
notifyListeners();
}
}现在您有一个完整的下拉列表,包括清晰的选择按钮。
https://stackoverflow.com/questions/60416928
复制相似问题