【问题标题】:Delete an item in the source list from a flutter ListView从颤动的 ListView 中删除源列表中的项目
【发布时间】:2021-08-03 01:28:06
【问题描述】:

我开始学习 Flutter,我正在尝试编写一个应用程序。

应用程序在 SwitchListTile 的 ListView 中有一个玩家列表。目前这是有效的。我正在尝试添加一个函数来从列表中删除其中一个玩家。

class PlayersSwitchListTilesContainer extends StatelessWidget {
  PlayersSwitchListTilesContainer({this.players});

  final List<PlayerModel> players;
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView(
        children : players.map<Widget>((PlayerModel p){
           return PlayerSwtichListTile(singlePlayer: p);
        }).toList()
      ),
    );
  }
}

class PlayerSwtichListTile extends StatefulWidget {
  PlayerSwtichListTile({this.singlePlayer});

  final PlayerModel singlePlayer;

  void removePlayer()
  {
    //  What goes here ???
    print('Delete ' + singlePlayer.playerName);
  }

  @override
  _PlayerSwtichListTileState createState() => new _PlayerSwtichListTileState(player: singlePlayer);
}

目前,当我尝试删除播放器时,它会调用正确的代码并打印播放器的名称。但是,我很难了解如何从players 列表中删除播放器。

如果有人有任何指点,我将不胜感激

【问题讨论】:

标签: flutter


【解决方案1】:

据我了解,要从玩家列表中删除玩家,您可以这样做,但对于这种方法,您需要手动提供索引号:

setState(() {
  players.removeAt(index);
});

更好的方法是使用 listView.builder 并向 PlayerSwtichListTile 添加一个按钮,该按钮可以从 listView.builder 接收索引,这样每当您单击该按钮时,PlayerSwtichListTile 播放器就会被删除:

ListView.builder(
  itemCount: players.length ?? 0,
  itemBuilder: (context, index) {
  return PlayerSwtichListTile(singlePlayer: p, index: index);}
)

class PlayerSwtichListTile extends StatefulWidget {
  PlayerSwtichListTile({this.singlePlayer, this.index});
  final int index;

  final PlayerModel singlePlayer;

  @override
  _PlayerSwtichListTileState createState() => new _PlayerSwtichListTileState(player: singlePlayer);
}

class _PlayerSwtichListTile extends State<PlayerSwtichListTile > {

  var player;
  _PlayerSwtichListTile({this.player});

  //call this function in ontap of that delete button
  void removePlayer()
  {
    setState(() {
    players.removeAt(widget.index);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

【讨论】:

  • 对延迟回复表示歉意。生活挡道了。谢谢,这给了我所需的解决方案
猜你喜欢
  • 2019-08-04
  • 2019-10-28
  • 1970-01-01
  • 2021-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多