您可能希望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
},