【问题标题】:How to get the index/key of the selected item in the list Flutter?如何获取列表 Flutter 中选中项的索引/键?
【发布时间】:2018-04-15 13:17:45
【问题描述】:

我正在使用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)
]
)
        ),
    )

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      您可能希望在ListView 中构建ListTiles 列表,并使用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 它有一个 @987654331 @ 参数,它也允许您按索引遍历列表。

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

      【讨论】:

      • 错误答案。您正在使用生成器。使用 listile 创建的小部件
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-25
      • 1970-01-01
      • 1970-01-01
      • 2013-05-17
      • 2022-07-06
      相关资源
      最近更新 更多