我试图制作一个dropdownButtonFormField,它有一个来自sqflite数据库的对象值列表。我发现列表项会显示出来,但是当我点击其中的一个项目时,它就会喊出一个错误。
class Test extends StatefulWidget {
@override
_TestState createState() => _TestState();
}
class _TestState extends State<Test> {
Section currentSection;
@override
Widget build(BuildContext context) {
final sectionsProvider = Provider.of<SectionsProvider>(context);
return Scaffold(
body: Container(
padding: EdgeInsets.all(15),
child: FutureBuilder<List<Section>>(
future: sectionsProvider.getSections(),
builder: (BuildContext context,AsyncSnapshot<List<Section>> snapshot){
if(!snapshot.hasData){
return Text('Loading...');
}else{
return DropdownButtonFormField<Section>(
//decoration: inputDecoration.copyWith(hintText: currentSection.title),
//value: currentSection,
items: snapshot.data.map((section){
return DropdownMenuItem<Section>(
value: section,
child: Row(
children: [
Icon(
Icons.brightness_1,
size: 15,
color: Color(section.color),
),
SizedBox(width: 20,),
Text(section.title),
],
),
);
},
).toList(),
isExpanded: false,
isDense: true,
onChanged: (value){
setState(() {
currentSection = value;
});
},
);
}
},
),
),
);
}
}
DropdownButtonFormField缺少参数值,因此你会得到这个错误。
解除下面的注释行将为你工作。
value: currentSection,
更新。
我认为问题在于你将整个对象赋值给值参数,下拉列表必须将值与下拉列表的值进行比较,以检查新的赋值是否在下拉项目列表中可用。
但是,在flutter(dart)中,我们不能直接比较对象。你必须覆盖==操作符和hascode,但我们可以使用Equatable包来轻松比较。
我不知道你的Section类,所以在下面的示例类中按照我所做的修改来做。
首先,加入 可等价 包在pubspec.yaml文件中。
class Section extends Equatable {
final int id;
Section({this.id});
@override
List<Object> get props => [id]; // pass all variable with(,) separated as i pass id.
}