Flutter中如何初始化List以引用其内置索引供后续使用?
Dart中如何在Widget里引用List的内置索引?
不用改写空List的初始化代码,Dart的List本身就自带索引,你在需要用索引的地方,直接通过遍历相关的方法获取就行,给你几种常用的实现方式:
用ListView.builder直接获取索引
这是Flutter Widget里最常用的方式,itemBuilder回调会直接传入当前元素的索引:List<String> example = []; // 先添加元素 example.addAll(['苹果', '香蕉', '橘子']); // 在Widget中使用 ListView.builder( itemCount: example.length, itemBuilder: (context, index) { // 这里的index就是List的内置索引 return ListTile( title: Text(example[index]), subtitle: Text('当前索引:$index'), ); }, );用asMap()转换为带索引的Map
把List转成键为索引、值为元素的Map,遍历这个Map就能同时拿到索引和元素:final indexedItems = example.asMap(); // 遍历示例 for (var entry in indexedItems.entries) { int index = entry.key; String item = entry.value; print('元素:$item,索引:$index'); } // 生成Widget示例 final widgets = indexedItems.entries.map((entry) { return ListTile( title: Text(entry.value), subtitle: Text('索引:${entry.key}'), ); }).toList();用forEachIndexed遍历(Dart 2.19+)
Dart 2.19及以上版本支持forEachIndexed方法,直接在遍历的时候拿到索引和元素:example.forEachIndexed((index, element) { print('元素:$element,索引:$index'); // 也可以在这里生成单个Widget,添加到组件列表中 });
核心逻辑就是:List的索引是它的固有属性,不需要在初始化时额外定义变量,只要在需要使用索引的场景下,通过对应的遍历方法就能直接获取。
内容的提问来源于stack exchange,提问作者mathems32
相关产品推荐
相关产品推荐

