[英]StateNotifierProvider: is it possible to control the value of different widgets in a form using a single StateNotifierProvider
class SearchFilterModel {
bool searchByDistance;
bool filterByStatusOpen;
String searchText;
...
}
class SearchFilterModelNotifier extends StateNotifier<SearchFilterModel> {
SearchFilterModelNotifier()
: super(SearchFilterModel(
searchByDistance: true,
filterByStatusOpen: false,
searchText: ''));
void updateSearchByDistance(bool searchByDistance) {
state.searchByDistance = searchByDistance;
}
void updateFilterByStatusOpen(bool filterByStatusOpen) {
state.filterByStatusOpen = filterByStatusOpen;
}
void updateSearchText(String searchText) {
state.searchText = searchText;
}
}
final searchFilterModelNotifierProvider = StateNotifierProvider<SearchFilterModelNotifier, SearchFilterModel>((ref) => SearchFilterModelNotifier());
class SearchForm extends ConsumerWidget {
@override
Widget build(context, watch) {
final searchFilterModelNotifier = watch(searchFilterModelNotifierProvider.notifier);
final searchFilterModel = watch(searchFilterModelNotifierProvider);
return Form(
child: Column(
children: [
SwitchListTile(
value: searchFilterModel.searchByDistance,
onChanged: (bool value) => searchFilterModelNotifier.updateSearchByDistance(value),
title: Text('Search by distance?')),
SwitchListTile(
value: searchFilterModel.filterByStatusOpen,
onChanged: (bool value) => searchFilterModelNotifier.updateFilterByStatusOpen(value),
title: Text('Filter by open status?')),
// not even sure how to do the text one if using a TextFormField
]
)
);
}
}
Okay with my project structured like this the values of the Switches aren't behaving as expected, their values aren't updating at all and I believe it's just that the widgets aren't rebuilding.好的,对于我这样结构的项目,Switch 的值没有按预期运行,它们的值根本没有更新,我相信这只是小部件没有重建。 I was able to make this work using a different state provider for each form field however when I have a lot of form fields it'd be way nicer to be able to have a single StateNotifierProvider that represents the entire form.我能够为每个表单字段使用不同的状态提供程序来完成这项工作,但是当我有很多表单字段时,能够拥有一个代表整个表单的单个 StateNotifierProvider 会更好。 Is this just something that's not possible?这只是不可能的事情吗?
The answer is to update the StateNotifier methods to something like答案是将 StateNotifier 方法更新为类似
void updateSearchByDistance(bool searchByDistance) {
state = SearchFilterModel(... searchByDistance: searchByDistance);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.