小编典典

如何获取列表Flutter中所选项目的索引/键?

flutter

我正在ListTile用来创建列表中的每个项目。每一项都是从数据数组动态创建的。ListTile提供onTap,但对我来说还不够,因为我需要通过获取键或索引来找出单击了哪个项目。

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

阅读 516

收藏
2020-08-13

共1个答案

小编典典

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