I'm loading data from api into my class UserProductType List<UserProductType> _visibleUserProductTypes = api();
. Then I'm using ListView.builder to create cards that have child GestureDetector so I can register clicks. (Then I would like to change card background and once button is pressed, sent the one chosen id to other function...)
The problem is that this code is not calling the function 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. 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
.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.