gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:31:16 27 4
gpt4 key购买 nike

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com