【问题标题】:How to delete listview item without dismissible如何在不关闭的情况下删除列表视图项目
【发布时间】:2020-01-11 22:24:31
【问题描述】:

我有一个 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);
                        }
                      ),

【问题讨论】:

  • 您是否没有使用某种List 的项目在您的ListView 中生成您的ListTiles?
  • 是的,我很困惑的是,当我按下按钮时,程序如何知道我点击了列表的哪个索引。有什么我可以访问的东西将按钮与瓷砖/索引的其余部分联系起来

标签: flutter


【解决方案1】:

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

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

【讨论】:

  • 我理解你的方法并会尝试实现它,当我点击每个图块旁边的按钮时是否会产生一个索引?这是我唯一缺少的部分。第三个瓷砖按钮单击与第二个按钮单击的区别是什么。一旦我可以根据按钮单击检索图块的索引,我就可以将它传递给 removeTile 方法
  • 您可以使用 ListView 构建器在此处为您提供的索引itemBuilder: (context,index){
  • 哦,我明白了,所以当我单击按钮时,itembuilder 会动态处理索引。谢谢,我会尝试实现这个
  • 你能更新你的代码吗?我也面临同样的问题。
  • @JoãoSoares 你能用代码更新你的答案吗,我需要它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-28
  • 1970-01-01
  • 2015-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-14
相关资源
最近更新 更多