[英]How to make ListView clickable in flutter?
I'm loading data from api into my class UserProductType List<UserProductType> _visibleUserProductTypes = api();
我正在将数据从 api 加载到我的类 UserProductType
List<UserProductType> _visibleUserProductTypes = api();
. . Then I'm using ListView.builder to create cards that have child GestureDetector so I can register clicks.
然后我使用 ListView.builder 创建具有子 GestureDetector 的卡片,以便我可以注册点击。 (Then I would like to change card background and once button is pressed, sent the one chosen id to other function...)
(然后我想更改卡片背景,按下按钮后,将选择的 ID 发送到其他功能......)
The problem is that this code is not calling the function onTap: () => selectItem(product),
问题是这段代码没有调用
onTap: () => selectItem(product),
函数onTap: () => selectItem(product),
Relevant part of the code:代码的相关部分:
void selectItem(UserProductType product) {
print(product.name);
}
Container listSection() {
return Container(
child: Expanded(
child: ListView.builder(
itemCount: _visibleUserProductTypes.length,
itemBuilder: (context, index) {
var product = _visibleUserProductTypes[index];
return new Card(
elevation: 2,
child: GestureDetector (
onTap: () => selectItem(product),
child: Container(
padding: EdgeInsets.all(15.0),
child: Row(
children: <Widget>[
Icon(_icons[index], color: Colors.grey,),
SizedBox(width: 10.0,),
Text(_visibleUserProductTypes[index].name,
style: TextStyle(color: _colors[index]),
),
],
),
),
),
);
},
),
)
);
}
Where is the problem?问题出在哪儿?
Wrap the entire Card
widget in a GestureDetector
widget.将整个
Card
小部件包装在GestureDetector
小部件中。 The code below should solve your issue:下面的代码应该可以解决您的问题:
return GestureDetector(
onTap: () => selectItem(product),
child: Card(
elevation: 2,
child: Container(
padding: EdgeInsets.all(15.0),
child: Row(
children: <Widget>[
Icon(_icons[index], color: Colors.grey,),
SizedBox(width: 10.0,),
Text(
_visibleUserProductTypes[index].name,
style: TextStyle(color: _colors[index]),
),
],
),
),
),
);
You can use ListTile
instead of Card
.您可以使用
ListTile
而不是Card
。
return ListTile(
onTap: () => selectItem(product),
leading: Icon(_icons[index], color: Colors.grey),
title: Text(_visibleUserProductTypes[index].name,
style: TextStyle(color: _colors[index]),
),
);
tapping the container inside the card might execute the function.轻敲卡内的容器可能会执行该功能。 or just make the gesture detector on the card and the hit on the tap which can give you the desired output
或者只是在卡片上制作手势检测器并点击水龙头,这可以为您提供所需的输出
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.