首页 > 解决方案 > 如何在不关闭的情况下删除列表视图项目

问题描述

我有一个 listTiles 列表,每个列表都有文本,旁边有一个按钮来删除磁贴。如果按钮被按下,用户确认他们想要删除它并且磁贴被移除。以前我使用了一个带键的可关闭小部件,但在这种情况下,我如何将列表中的项目与我需要删除的图块相关联。

代码(忽略 onTap(),底部的 flatButtons 用作提示):

ListView.builder(
  itemCount: subGoals.length,
  itemBuilder: (context,index){
    return Card(
      color: Colors.grey[500],
      child: ListTile(
        onTap: (){
          //should make new list with the title of the ListTile's text
        },
        title: Text(subGoals[index],
          style: TextStyle(color: Colors.white,fontSize: 35),
        ),
        trailing: IconButton(
          icon: Icon(Icons.close),
          color: Colors.white,
          splashColor: Colors.red[600], 
          onPressed: (){
            showDialog(
              context: context,
              builder: (BuildContext context){
                return AlertDialog(
                  title: Center(child: Text("Delete List?", style: TextStyle(fontSize: 25))),
                  content: Row(
                    mainAxisSize: MainAxisSize.min,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      FlatButton(
                        child: Text("Yes", style: TextStyle(fontSize: 22)),
                        onPressed: (){
                          if(true){
                             //removeTile method goes here
                          }
                        }
                      ),
                      FlatButton(
                        child: Text("No", style: TextStyle(fontSize: 22)),
                        onPressed: (){
                          Navigator.pop(context);
                        }
                      ),

标签: flutter

解决方案


如果我从问题和评论中正确理解了您的问题,那么您应该有一个从您调用的方法来从您ListTile的 item 中删除该项目List。您应该将您index生成的传递ListView给该方法,并使用它从与索引匹配的位置从列表中删除项目。然后你setState()用来确保你的列表在你的 ListView 上重新呈现。

如果您没有此方法并且需要帮助编写它,请分享更多代码和评论,我将更新此答案。


推荐阅读