[英]Update Flutter ListTile with tap not working
目標是在點擊時將前導和副標題的ListTile中的值更改為 null。 點擊正在切換_act boolean,但 ListTile 的前導:和副標題:值不會從它們的初始 state 改變。 我的 ListView 代碼如下。 請幫忙。
return new ListView(
children: querySnapShot.data.documents.map((DocumentSnapshot document) {
bool _act = false;
return new ListTile(
leading: _act != false ? const Icon(Icons.remove_red_eye, color: Color(0xff00caff), size: 40) : null,
title: new Text((DBProvider.db.idDeHasher(document['exampleid'], key) ?? 'fallback'), style: TextStyle(color: secondaryColor)),
subtitle: _act != false ? new Text((document['exampleString'] ?? 'fallbackString'), style: TextStyle(color: secondaryColor)) : null,
onTap: () {
_act = !_act;
print(_act.toString());
}
);
}).toList(),
);
您需要使您的小部件成為Stateful Widget
,並在ListTile
上點擊時調用setState
。
根據文檔:
Calling setState notifies the framework that the internal state of this object has changed in a way that might impact the user interface in this subtree, which causes the framework to schedule a build for this State object.
因此,如果小部件的 state 發生更改,您必須調用setState
來觸發視圖的重建並立即看到新 state 所暗示的更改。
我以您的代碼為例添加了一個演示:
// define a list of acts
List _acts = [];
return new ListView(
children: querySnapShot.data.documents.asMap().entries.map((entry) {
// declare all entries of the list to false
acts.add(false);
// access the index
int index = entry.key;
// access the document
DocumentSnapshot document = entry.value;
// DocumentSnapshot document = entry
return new ListTile(
leading: _acts[index] != false ? const Icon(Icons.remove_red_eye, color: Color(0xff00caff), size: 40) : null,
title: new Text((DBProvider.db.idDeHasher(entry.val['exampleid'], key) ?? 'fallback'), style: TextStyle(color: secondaryColor)),
subtitle: _acts[index] != false ? new Text((document['exampleString'] ?? 'fallbackString'), style: TextStyle(color: secondaryColor)) : null,
onTap: () {
// call setstate
setState(() { // new line
// change the bool variable based on the index
_acts[index] = !_acts[index];
print(_acts[index].toString());
});
}
);
}).toList(),
);
onTap: () {
setState((){
_act = !_act;
print(_act.toString());
}
});
只需復制並粘貼它,它就可以工作。
替換bool _act = false;
略低於
class _SomeClass extends State<SomeClass> {
並用setState({});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.