繁体   English   中英

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

[英]How to get the index/key of the selected item in the list 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)
]
)
        ),
    )

你想建立自己的列表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
      }, 

您可以使用捕获项目信息的闭包创建ListTile实例。 在此示例中,使用ListTile的每个Text的标签调用_tappedFolder函数。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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