Flutter:DropdownMenuItem如何获取当前项的索引i?
问题描述
我尝试访问计数器变量i或当前DropdownMenuItem的索引,但始终无法实现。代码示例如下:
items: listeZutatenDropdown[i].map((String value) { return DropdownMenuItem( value: value, child: (value == "Zutat auswählen") ? new Text("Zutat auswählen") : new Text(value + " " + i.toString()), ); }).toList()
按上述代码打印i时,结果始终为0。尝试使用带索引的map方法时,出现类型不匹配错误:
"The argument type 'List' can't be assigned to the parameter type 'List
?'"
"The argument type 'DropdownMenuItem Function(int, String)' can't be assigned to the parameter type 'dynamic Function(String)'"
我也曾尝试将i存入变量后在return语句中访问,但结果仍为0。希望能告知问题所在!
问题原因与解决方法
1. i始终为0的原因
这是闭包捕获变量的特性导致的:如果i是在循环中定义的,map的回调会捕获i的引用而非当前循环的数值。当循环结束后,i最终停在终止时的数值(比如单循环从0开始就会是0),所有回调都会引用这个最终值。
2. 带索引的map报错解决方式
Dart的List提供asMap()方法,可将列表转为Map<int, String>(键为索引,值为元素)。遍历这个Map即可同时获取索引和值,且需明确指定DropdownMenuItem的类型,避免类型不匹配:
items: listeZutatenDropdown[i].asMap().entries.map((entry) { int index = entry.key; String value = entry.value; return DropdownMenuItem<String>( value: value, child: (value == "Zutat auswählen") ? const Text("Zutat auswählen") : Text("$value $index"), ); }).toList()
3. 闭包捕获问题的额外解决方案
如果是在循环中创建多个Dropdown,需确保每个回调捕获当前循环的i值,可在循环内部创建局部变量保存当前i:
for (int i = 0; i < listeZutatenDropdown.length; i++) { int currentIndex = i; items: listeZutatenDropdown[currentIndex].map((String value) { return DropdownMenuItem<String>( value: value, child: (value == "Zutat auswählen") ? const Text("Zutat auswählen") : Text("$value $currentIndex"), ); }).toList() }
内容的提问来源于stack exchange,提问作者Goku
相关产品推荐
相关产品推荐

