Flutter如何遍历渲染预定义Widget列表并解决DropdownButton相关报错
错误原因与修复方案
1. 语法错误:Unexpected text 'return'
Dart的箭头函数=>属于简写语法,后面直接跟返回的表达式,不需要额外加return关键字,加了就会报语法错误。
2. 类型不匹配错误
有两个问题导致类型不兼容:
- 定义
grades列表时,没有给DropdownMenuItem指定泛型为String,默认推断为dynamic,和DropdownButton<String>要求的DropdownMenuItem<String>类型不匹配 map方法返回的是Iterable类型,而items参数要求传入List类型,需要调用toList()方法转换类型
修复后的完整代码
首先修改grades的定义:
final List<DropdownMenuItem<String>> grades = <DropdownMenuItem<String>>[ DropdownMenuItem(value: "Highschool", child: Text('Highschool')), DropdownMenuItem(value: "Senior High", child: Text('Senior High')), DropdownMenuItem(value: "College", child: Text('College'))];
然后修改DropdownButton的items配置:
Form( child: DropdownButtonHideUnderline( child: ButtonTheme( alignedDropdown: true, child: DropdownButton<String>( value: defState, onChanged: (String? newValue) { setState(() { defState = newValue!; }); }, // 这里去掉return,末尾加toList() items: grades.map((item) => item).toList(), hint: Text("Grade"), ), ) ), )
如果你不想修改原grades的泛型定义,也可以在map的时候手动指定泛型做类型转换:
items: grades.map<DropdownMenuItem<String>>((item) => item as DropdownMenuItem<String>).toList()
内容的提问来源于stack exchange,提问作者Jam
相关产品推荐
相关产品推荐

