0

I'm starting to learn Flutter and I'm trying to write an application.

The application has a list of players in a ListView of SwitchListTile. This is working at the moment. I'm trying to add a function to delete one of the players from the lists.

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);
}

At the moment, when I try to delete a player it calls the correct code and prints the player's name. However, I'm struggling to see how to delete the player from the players list.

I'd be grateful for any pointers anyone has

Ian Boggs
  • 466
  • 3
  • 14

1 Answers1

0

From what I understand, to delete a player from the list of players you can do this but for this method, you need to provide the index number manually:

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

A better approach would be to use a listView.builder and add a button to the PlayerSwtichListTile which can receive the index from listView.builder so that whenever you click that button then that PlayerSwtichListTile player would get removed:

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();
  }
}
Deepanshu
  • 509
  • 1
  • 12
  • 1
    Apologies for the delay in responding. Life got in the way. Thank you, this gave me the solution I required – Ian Boggs May 23 '21 at 18:14