_t-6ren">
gpt4 book ai didi

flutter - Flutter下拉菜单无法使用提供商更改文本

转载 作者:行者123 更新时间:2023-12-03 04:54:09 25 4
gpt4 key购买 nike

我有代表当前所选项目的此类:

class DropdownText with ChangeNotifier {

String _text = "";

String get text => _text;

void setText(String value) {
_text = value;
notifyListeners();
}

}

这是我用来尝试显示下拉按钮的代码:
class DropDown extends StatelessWidget {

final List<DropdownMenuItem<String>> menu = [
DropdownMenuItem<String>(
value: "A",
child: Text("A"),
),
DropdownMenuItem<String>(
value: "B",
child: Text("B"),
)
];

DropDown();

@override
Widget build(BuildContext context) {
return FormField<String>(
builder: (FormFieldState<String> formState) {
return Consumer<DropdownText>(
builder: (context, dropdown, _) {
return InputDecorator(
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)
),
prefixIcon: const Icon(Icons.fastfood),
),
child: DropdownButtonFormField<String>(
items: menu,
onChanged: (value) {
dropdown.setText(value);
},
value: dropdown.text,
),
);
},
);
},
);
}

}

我得到的错误是

Failed assertion: line 1411 pos 15: 'items == null || items.isEmpty || value == null || I/flutter ( 7719):
items.where((DropdownMenuItem item) { I/flutter ( 7719):
return item.value == value; I/flutter ( 7719): }).length == 1'



但是我在哪里失败?我明确地将每个泛型类型。可能是提供程序包中的 Consumer<T>问题吗?

此外,我在下拉列表中没有看到重复项,也没有空项目。

最佳答案

当您阅读此部分错误时

 items.where((DropdownMenuItem<T> item) {return item.value == value;}).length == 1'

您会注意到,如果长度为0,则仍会标记错误

基本上,下拉列表的初始值必须为一个DropDownItem。并且由于您的初始值为“”,并且没有以“”为值的DropDownItem,因此它将无法正常工作
 String _text = "";

解决方案

将DropDownText中的 _text 的初始值设置为项目的第一个值(DropDownItems)
class DropdownText with ChangeNotifier {

String _text = "A";

String get text => _text;

void setText(String value) {
_text = value;
notifyListeners();
}

}

关于flutter - Flutter下拉菜单无法使用提供商更改文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60868985/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com