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)
]
)
),
)
In Dart, the List class has 4 methods that can help you find the index of a specific element in a list: indexOf: Returns the first index of the first element in the list that equals a given element. Returns -1 if nothing is found. indexWhere: Returns the first index in the list that satisfies the given conditions.
you can use last property for read/write, inherited-getter: last is a returns the last element from the given list.
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")));
},
);
})
),
);
}
}
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
},
You can create ListTile instances with closures that capture item information. In this example, the _tappedFolder function is called with the label of each Text of the ListTile.
List<ListTile> _buildFolderTiles() {
var list = List<ListTile>();
for (var each in ['A:','B:','C:','D:']) {
list.add(ListTile(
title: Text(each),
onTap: (){ _tappedFolder(each); }
));
}
return list;
}
void _tappedFolder(String which) {
print("tapped ${which}");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With