grepLines
grepLines

Reputation: 2558

How to get the index/key of the selected item in the list Flutter?

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)
]
)
        ),
    )

Upvotes: 21

Views: 45012

Answers (2)

emicklei
emicklei

Reputation: 1381

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}");
  }

Upvotes: 6

Shady Aziza
Shady Aziza

Reputation: 53337

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:

enter image description here

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
      }, 

Upvotes: 15

Related Questions