Har*_*hit 5 dropdown flutter flutter-widget flutter-dropdownbutton
当我尝试使用 flutter DropdownButton Widget 时,我在控制台中收到此错误。
package:flutter/src/material/dropdown.dart': 断言失败: 第 1252 行 pos 12: 'widget.items!.where((DropdownMenuItem item) => item.value == widget.value).length == 1' : 不是真的。
有一个很长的回溯...这里我添加了小代码示例,它将重现此错误...任何人都可以简单地复制粘贴到main.dart文件中
// flutter import
import 'package:flutter/material.dart';
void main() {
runApp(const BugReportApp());
}
class BugReportApp extends StatefulWidget {
const BugReportApp({Key? key}) : super(key: key);
@override
State<BugReportApp> createState() => _BugReportAppState();
}
class _BugReportAppState extends State<BugReportApp> {
final TextEditingController _dropdownController = TextEditingController();
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Bug Report',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Flex(direction: Axis.vertical, children:[
DropdownButton<String>(
value: _dropdownController.text == ""
? null
: _dropdownController.text,
items: ["hello, world", "how are you", "goodbye"]
.map((_value) => DropdownMenuItem<String>(
child: Text(
_value,
)))
.toList(),
onChanged: (_value) {
setState(() {
_dropdownController.text = _value ?? _dropdownController.text;
});
},
),
],),
);
}
}
Run Code Online (Sandbox Code Playgroud)
我原本期望 dropdown 能够正常工作,但我不知道为什么它没有正常工作。
Md.*_*ikh 10
你失踪value了DropdownMenuItem。
.map((_value) => DropdownMenuItem<String>(
value: _value, // this
child: Text(
_value,
)))
Run Code Online (Sandbox Code Playgroud)
还要确保Scaffold在家里使用。
试试这个代码,还在代码中添加了一些解释:
class _MyHomePageState extends State<MyHomePage> {
final TextEditingController _dropdownController = TextEditingController();
String? dropDownValue = 'hello, world'; // add one value as the defaul one which must exists in the dropdown value
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Column(
children: [
Flex(direction: Axis.vertical, children:[
DropdownButton<String>(
value: dropDownValue, // this place should not have a controller but a variable
onChanged: (_value) {
setState(() {
dropDownValue = _value;
});
},
items: ["hello, world", "how are you", "goodbye"]
.map<DropdownMenuItem<String>>((String _value) => DropdownMenuItem<String>(
value: _value, // add this property an pass the _value to it
child: Text(_value,)
)).toList(),
),
])
],
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5646 次 |
| 最近记录: |