【问题标题】:Flutter) I wonder how to remove items from the created list by pressing the buttonFlutter)我想知道如何通过按下按钮从创建的列表中删除项目
【发布时间】:2022-01-13 06:05:13
【问题描述】:

我按下按钮将 ListTile 小部件添加到列表并将其输出到 ListViewBuilder。我想通过按每个列表上的删除按钮来删除列表。

  List<ListTile> _todoList = [];

添加列表按钮

 TextButton.icon(
  onPressed: () {
     //I wrote the text in a TextField in the Dialog Widget.
     //And add ListTile widget to list
     _todoList.add(_addListTile(_textController.text));
  }

输出列表

  ListView.builder(
      itemBuilder: (context, index) {
         return _todoList[index];
      },
              
      itemCount: _todoList.length),

这是一个添加到列表中的小部件。我想通过按下列表磁贴上的按钮来删除列表的索引。

  _addListTile(String text) {
    return ListTile(
      title: Text(text),
      //menu 
      trailing: PopupMenuButton(
        // icon: const Icon(Icons.more_vert),
        itemBuilder: (context) {
          return [const PopupMenuItem<int>(value: 0, child: Text('Remove'))];
        },
        //Cliked menu 
        onSelected: (item) {
          switch (item) {
            case 0:
              return print('Remove List');
              // return _todoList.remove();
          }
        },
      ),
      onTap: () {},
    );
  }

如何使用此 ListTile 上的删除按钮删除列表?

谢谢。

【问题讨论】:

    标签: android ios flutter


    【解决方案1】:

    我认为您可以为每个 ListTile 对象添加一个 key 值,以确定您每次在 _addListTile() 函数中生成哪个 ListTile 时要删除它,如下所示。

      _addListTile(String text) {
        // You can have anything to be the unique value. Here, I just used the current time.
        // I can't say this is the best option.
        final key = ValueKey(DateTime.now().toString()); 
    
        return ListTile(
          key: key,
          title: Text(text),
          //menu 
          trailing: PopupMenuButton(
            // icon: const Icon(Icons.more_vert),
            itemBuilder: (context) {
              return [const PopupMenuItem<int>(value: 0, child: Text('Remove'))];
            },
            //Cliked menu 
            onSelected: (item) {
              switch (item) {
                case 0:
                  print('Remove List');
                  return _todoList.removeWhere((e) => e.key == key);
              }
            },
          ),
          onTap: () {},
        );
      }
    

    我希望它对你有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-28
      • 1970-01-01
      • 2023-01-25
      • 2019-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多