你好,当我尝试时,我从浏览器复制了代码,发生了错误,我如何解决它,因为我想使用此代码作为学习中的参考,但发生以下错误
异常发生。
_AssertionError ('package:flutter/src/material/dropdown.dart': Failed assertion: line 1584 post 15: 'items == null || items.isEmpty || value == null ||
items.where((DropdownMenuItem<T> item) {
return item. value == value;
}).length == 1': There should be exactly one item with [DropdownButton]'s value: Dropdown 1.
Either zero or 2 or more [DropdownMenuItem]s were detected with the same value)
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: DynamicDropdown(),
);
}
}
class DynamicDropdown extends StatefulWidget {
@override
_DynamicDropdownState createState() => _DynamicDropdownState();
}
class _DynamicDropdownState extends State<DynamicDropdown> {
String dropdownValue1 = 'Dropdown 1';
String dropdownValue2 = 'Dropdown 2';
List<String> dropdownItems1 = ['Item 1', 'Item 2', 'Item 3'];
List<String> dropdownItems2 = ['Item A', 'Item B', 'Item C'];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Dynamic Dropdown'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DropdownButtonFormField(
value: dropdownValue1,
onChanged: (newValue) {
setState(() {
dropdownValue1 = newValue!;
if (dropdownValue1 == 'Item 1') {
dropdownItems2 = ['Item A', 'Item B', 'Item C'];
} else if (dropdownValue1 == 'Item 2') {
dropdownItems2 = ['Item D', 'Item E', 'Item F'];
} else {
dropdownItems2 = ['Item G', 'Item H', 'Item I'];
}
});
},
items: dropdownItems1.map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
SizedBox(height: 20),
DropdownButton<String>(
value: dropdownValue2,
onChanged: (newValue) {
setState(() {
dropdownValue2 = newValue!;
});
},
items: dropdownItems2.map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
],
),
),
);
}
}
你的'dropdownValue1'应该来自'dropdownItems1'列表。错误来自这里- 'value: dropdownValue1',你从列表外分配了一个项目,检查下面的代码,我已经编辑了你的代码;
// String dropdownValue1 = 'Dropdown 1';
// String dropdownValue2 = 'Dropdown 2';
List<String> dropdownItems1 = ['Item 1', 'Item 2', 'Item 3'];
List<String> dropdownItems2 = ['Item A', 'Item B', 'Item C'];
String dropdownValue1;
String dropdownValue2;
@override
void initState() {
// TODO: implement initState
super.initState();
dropdownValue1 = dropdownItems1[0];
dropdownValue2 = dropdownItems2[0];
}