[英]How to make ListView clickable in flutter?
我正在將數據從 api 加載到我的類 UserProductType List<UserProductType> _visibleUserProductTypes = api();
. 然后我使用 ListView.builder 創建具有子 GestureDetector 的卡片,以便我可以注冊點擊。 (然后我想更改卡片背景,按下按鈕后,將選擇的 ID 發送到其他功能......)
問題是這段代碼沒有調用onTap: () => selectItem(product),
函數onTap: () => selectItem(product),
代碼的相關部分:
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]),
),
],
),
),
),
);
},
),
)
);
}
問題出在哪兒?
將整個Card
小部件包裝在GestureDetector
小部件中。 下面的代碼應該可以解決您的問題:
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]),
),
],
),
),
),
);
您可以使用ListTile
而不是Card
。
return ListTile(
onTap: () => selectItem(product),
leading: Icon(_icons[index], color: Colors.grey),
title: Text(_visibleUserProductTypes[index].name,
style: TextStyle(color: _colors[index]),
),
);
輕敲卡內的容器可能會執行該功能。 或者只是在卡片上制作手勢檢測器並點擊水龍頭,這可以為您提供所需的輸出
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.