简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM