如何获取列表Flutter中所选项目的索引/键?
问题内容:
我正在ListTile
用来创建列表中的每个项目。每一项都是从数据数组动态创建的。ListTile
提供onTap
,但对我来说还不够,因为我需要通过获取键或索引来找出单击了哪个项目。
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)
]
)
),
)
问题答案:
您可能希望ListTile
在内构建的列表ListView
,并使用List.generate
构造函数来获取的索引,children
这是一个简单的示例:
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")));
},
);
})
),
);
}
}
请记住,这种方法List.generate
在小列表上也能很好地工作,如果您正在阅读可扩展列表(例如,用户列表),则需要使用ListView.builder
而不是一个ListView
带有builder
参数的参数,该参数也允许您按索引遍历列表。
new ListView.builder(itemBuilder: (BuildContext context, int index) {
//return your list
},