问题描述
我想在Riverpod中使用changenotifierProvider创建DropDownButton,但是我不能很好地编写我的代码.请帮我.我想,我只是写了"watch"方法,但我不知道该怎么读.因此,它应该显示所选择的项目,并且还应该使用provider.Category进行更新.
I want to create DropDownButton with changenotifierProvider in Riverpod, but i can not write nicely my code. Please help me. I suppose, i just wrote 'watch' method, but i do not know how to read it. So, it should show the item which is chosen, and also it should be update with provider.Category.
我的DropDownButton代码在这里:
My DropDownButton code is here:
Widget dropdownButton(BuildContext context,watch) {
String constantValue = "League Of Legends";
final postProvider = ChangeNotifierProvider<PostProvider>((ref) => PostProvider());
final provider = watch(postProvider);
return Consumer(
builder: (context, watch, _) {
return DropdownButton(
value: provider.postCategory ?? constantValue,
onChanged: (newValue) {
provider.postCategory = newValue;
},
items: <String>["League Of Legends", "Steam", "Csgo"]
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
onTap: () => value,
value: value ?? constantValue,
child: Text(value ?? constantValue),
);
}).toList());
},
);
}
这里是我的DropDownButton图像:(当我选择列表中的任何项目时,它都无法正常工作.它始终选择第一个(它选择"League of Legends").
Here my DropDownButton Image: ( when i choose any item of the list, it can not work properly. It always pick the first one (It picks "League of Legends").
我选择了Steam,但卡类别显示了英雄联盟
I select steam but card categoty shows League of legends
推荐答案
final postProvider =
ChangeNotifierProvider<PostProvider>((ref) => PostProvider());
class PostProvider extends ChangeNotifier {
String _postCategory;
String get postCategory => _postCategory;
categoryOnChanged(String value) {
if (value.isEmpty) {
return _postCategory;
}
_postCategory = value;
print(_postCategory);
return notifyListeners();
}
}
class DropDownPage extends StatefulWidget {
@override
_DropDownPageState createState() => _DropDownPageState();
}
class _DropDownPageState extends State<DropDownPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Dropdown Riverpod issue"),
),
body: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: Center(
child: _DropDownWidgetConsumer(),
),
),
);
}
}
class _DropDownWidgetConsumer extends ConsumerWidget {
@override
Widget build(BuildContext context, ScopedReader watch) {
final category = watch(postProvider).postCategory;
return DropdownButton(
hint: Text("Choose category"),
value: category,
items: <String>["League Of Legends", "Steam", "Csgo"]
.map((e) => DropdownMenuItem<String>(
onTap: () => e,
value: e ?? category,
child: Text(e ?? "$category"),
))
.toList(),
onChanged: (value) {
context.read(postProvider).categoryOnChanged(value);
},
);
}
}
这篇关于如何使用Riverpod Notifier创建drowdownbutton?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!