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

标签 dart flutter

I'm using ListTile to create each item in the list. Each item is created dynamically from the data array. ListTile 提供了onTap,但对我来说还不够,因为我需要通过获取key 或index 来找出点击了哪个item。

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

最佳答案

您可能希望在 ListView 中构建您的 ListTile 列表,并使用 List.generate 构造函数来获取children 这里是一个简单的例子:

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

      ),
    );
  }
}

请记住,List.generate 适用于小型列表,如果您正在阅读可扩展列表(例如:用户列表),则需要使用 ListView.builder 而不是 ListView 它有一个 builder 参数,允许您按索引循环遍历列表。

new ListView.builder(itemBuilder: (BuildContext context, int index) {
        //return your list
      }, 

关于dart - 如何获取列表 Flutter 中选中项的索引/键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47085070/

相关文章:

dart - 是否可以让 dartdoc 显示对属性的评论

flutter 芯片和颜色 - 为什么 ChoiceChip 如此不同

flutter - 了解使用特定 ID 进行 Getx 状态更新如何与 SetState((){}) 配合使用

android - 将文本放在 CircularProgressIndicator 的中心

Flutter 从 future<File> 创建字符串以检查文件名的最后 3 个字符

DART:如何绑定(bind)单选按钮值属性

amazon-web-services - Flutter - 仅使用 aws key 和 key 上传 AWS S3 图像(不使用任何包/SDK)

Dart:异步抽象方法

dart - Angular.dart 禁用路由?

dart - 如何防止所选屏幕上的设备方向发生变化