我想我想要一个如此简单的东西,flutter 告诉我只有一个项目或没有项目。但我确信项目不止一个,IDK,我应该如何针对这个问题提出问题。我只想获取一个列表并使用 CustomClass 的项目制作一个下拉菜单。我确实从 https://api.flutter.dev/flutter/material/DropdownButton-class.html 复制粘贴,这是可行的,但是当我使用以下命令更改数据时矿 ....
import 'package:flutter/material.dart';
class BreedJson {
final String breed;
final String img;
BreedJson(this.breed, this.img);
}
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const Center(
child: MyStatefulWidget(),
),
),
);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
String dropdownValue = 'default ';
final List<BreedJson> myBreedJson = [
BreedJson("Cavalier King Charles Spaniel",
'https://images.pexels.com/photos/104827/cat-pet-animal-domestic-104827.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500'),
BreedJson('Curly-Coated Retriever',
'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSLqpKzfZ6L0TSvUKBhXwJQOnqfWzoaQWoIjCZu1s0evNhfSFWeNVMYWJYt0MqInbznRgE&usqp=CAU')
];
@override
Widget build(BuildContext context) {
return DropdownButton<String>(
value: dropdownValue,
icon: const Icon(Icons.arrow_downward),
elevation: 16,
style: const TextStyle(color: Colors.deepPurple),
underline: Container(
height: 2,
color: Colors.deepPurpleAccent,
),
onChanged: (String? newValue) {
setState(() {
dropdownValue = newValue!;
});
},
items: myBreedJson
.map<DropdownMenuItem<String>>((BreedJson value) => DropdownMenuItem<String>(
value: value.breed,
child: Text(value.img),
))
.toList());
}
}
试试这个:
String dropdownValue = "Cavalier King Charles Spaniel";
myBreedJson
列表不包含default
,这就是它抛出此错误的原因。
您可以在值上传递最初为 null 的值,这样可以使
dropdownValue
可空
String? dropdownValue;
该错误是不言自明的,有时会令人困惑,因为它结合了很多组合。然而,提示位于第一行
There should be exactly one item with [DropdownButton]'s value: default
,超出了以下例外
I/flutter ( 9860): There should be exactly one item with [DropdownButton]'s value: default.
I/flutter ( 9860): Either zero or 2 or more [DropdownMenuItem]s were detected with the same value
I/flutter ( 9860): 'package:flutter/src/material/dropdown.dart':
I/flutter ( 9860): Failed assertion: line 1666 pos 15: 'items == null || items.isEmpty || value == null ||
I/flutter ( 9860): items.where((DropdownMenuItem<T> item) {
I/flutter ( 9860): return item.value == value;
I/flutter ( 9860): }).length == 1'
但最重要的是它无法选择值
'default'
因此,默认值应与为下拉列表提供的可能值之一匹配。
就我而言,我遇到了一个愚蠢的问题,我渲染了两个下拉列表,但是由于复制粘贴问题,两者都绑定到相同的状态变量作为初始值。
因此,当我更改一个并重新渲染时,它期望其他下拉列表中有相同的项目,但该项目不可用,我正在挠头到底出了什么问题。
因此,请仔细检查您的逻辑以设置初始值。