Want to get the index/key of the selected item in the list Flutter? You would want to build your list of ListTiles within a ListView, and use List.generate constructor to get the index of the children here is a simple example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | 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"))); }, ); }) ), ); } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.