繁体   English   中英

更新 Flutter ListTile 与水龙头不工作

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM