我想将List转换为Map并只获得'CourseName',我该如何做到这一点?
这是模型
`class Course {
final int courseCategoryId;
final int courseSubCategoryId;
final int courseId;
final Color onlineTrueColor;
final String coverImgCourse;
final String courseName;
final String courseTeaserText;
final int courseTutorId;
final String courseGrads;
final int coursePrice;
final String courseCashBack;
final bool isCourseOnline;
final String courseDescription;
Course ( {
this.courseDescription,
this.courseCategoryId,
this.courseSubCategoryId,
this.courseId,
this.onlineTrueColor,
this.coverImgCourse,
this.courseName,
this.courseTeaserText,
this.courseTutorId,
this.courseGrads,
this.coursePrice,
this.courseCashBack,
this.isCourseOnline,
});
} `
(我需要将其转换为map,因为我需要将其用于下拉列表,它只适用于map,如果你认为可能有其他解决方案请与我分享)
DropdownButtonHideUnderline(
child: ButtonTheme(
alignedDropdown: true,
child: DropdownButton<String>(
isDense: true,
hint: Text('Выберите категорию'),
value: _selected,
onChanged: (String newValue) {
setState(() {
_selected = newValue;
});
},
items: _course.map((Map map) {
return new DropdownMenuItem<String>(
value: map["id"].toString(),
child: Row(
children: <Widget> [
Container(
margin: EdgeInsets.only(left: 10),
child: Text(map['courseName']),
)
],
));
}).toList(),
),
),)
您不需要将其转换为映射。使用列表是可以的。如果您注意到,在项目的末尾,在构建它们之后,将调用. tolist()方法。最后,您将创建一个DropdownMenuItem列表。
解决方案:你可以使用list. generate()方法,直接从列表中构建所有的项目。
你的代码应该是这样的:items: List.generate(yourList.length, (index) =>
return DropdownMenuItem<String>(
value: yourList[index].id.toString(),
child: Row(
children: <Widget> [
Container(
margin: EdgeInsets.only(left: 10),
child: Text(yourList[index].courseName),
)
],
)
);
),