如何获取列表Flutter中所选项目的索引/键? [英] How to get the index/key of the selected item in the list Flutter?
问题描述
我正在使用 ListTile
创建列表中的每个项目。每个项目都是从数据数组动态创建的。 ListTile
提供了 onTap
,但这对我来说是不够的,因为我需要通过选择键或索引。
I'm using ListTile
to create each item in the list. Each item is created dynamically from the data array. ListTile
provides onTap
, but it's insufficient for me, because I need to find out which item is clicked by either getting the key or index.
ListTile:
new ListTile(
//leading: const Icon(Icons.flight_land),
title: const Text('Trix\'s airplane'),
subtitle: const Text('The airplane is only in Act II.'),
enabled: true,
onTap: () { //TODO: get the identifier for this item },
trailing: new Container(
child: new Row(
children: [
new Text("70%"),
const Icon(Icons.flight_land)
]
)
),
)
推荐答案
您要构建<$ c $的列表 ListView
中的c> ListTile ,并使用 List.generate
构造函数获取孩子
的索引,这是一个简单的示例:
You would want to build your list of ListTile
s within a ListView
, and use List.generate
constructor to get the index of the children
here is a simple example:
import "package:flutter/material.dart";
class ListTest extends StatefulWidget {
@override
_ListTestState createState() => new _ListTestState();
}
class _ListTestState extends State<ListTest> {
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
int _id;
@override
Widget build(BuildContext context) {
return new Scaffold(
key: _scaffoldKey,
appBar: new AppBar(title: new Text("List"),),
body: new ListView(
children: new List.generate(10, (int index){
return new ListTile(title: new Text("item#$index"),
onTap:(){
setState((){
_id = index; //if you want to assign the index somewhere to check
});
_scaffoldKey.currentState.showSnackBar(new SnackBar(content: new Text("You clicked item number $_id")));
},
);
})
),
);
}
}
请记住列表.generate
可以用于较小的列表,如果您正在阅读可扩展列表(例如:用户列表),则需要使用 ListView.builder
而不是 ListView
,它具有一个 builder
参数,该参数还允许您按索引遍历列表。
Keep in mind that List.generate
works fine with small lists, if you are reading in an extendable list (e.g: a list of users) you need to use ListView.builder
instead of a ListView
it has a builder
argument that allow you to loop over your list by index as well.
new ListView.builder(itemBuilder: (BuildContext context, int index) {
//return your list
},
这篇关于如何获取列表Flutter中所选项目的索引/键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!