MURALI KRISHNAN MT
MURALI KRISHNAN MT

Reputation: 195

How to remove Map from list in Dart | Flutter

I have a json list. from this i want to delete a particular item. Below is my code.

final List _vehicleList = [
    {
      'vehicleNumber': 'KL-14-V-5208',
      'vehicleType': 'Two Wheeler',
    },
    {
      'vehicleNumber': 'KL-13-H-8880',
      'vehicleType': 'Four Wheeler',
    },
    {
      'vehicleNumber': 'KL-14-M-6889',
      'vehicleType': 'Three Wheeler',
    },
  ];

This is my list. Here from this i want to delete the item based on vehicleNumber when i press a delete button. I'am using listview builder. When i print the list after the button press nothing happens This is my UI Code.

                       return Column(
                            children: [
                              Padding(
                                padding: const EdgeInsets.all(12.0),
                                child: Text(
                                  _vehicleList[index]['vehicleNumber'],
                                ),
                              ),
                              Padding(
                                padding: const EdgeInsets.all(12.0),
                                child: Text(
                                  _vehicleList[index]['vehicleType'],
                                ),
                              ),
                              GestureDetector(
                                onTap: () {
                                  print('Deleted');
                                  _vehicleList.removeAt(_vehicleList[index]);
                                  print(_vehicleList);
                                },
                                child: const Padding(
                                  padding: EdgeInsets.all(12.0),
                                  child: Icon(
                                    FontAwesomeIcons.timesCircle,
                                    color: Colors.redAccent,
                                  ),
                                ),
                              ),
                            ],
                          );

Upvotes: 1

Views: 3752

Answers (2)

Ravindra S. Patil
Ravindra S. Patil

Reputation: 14785

Try below code hope its help to you. just pass your index

_vehicleList.removeWhere((element) => element["vehicleNumber"] == 'KL-14-V-5208');

Upvotes: 2

Salih Can
Salih Can

Reputation: 1801

You should change like this;

Before;

_vehicleList.removeAt(_vehicleList[index]);

after

_vehicleList.removeAt(index);

Documentation of how to use the "removeAt" method. https://api.flutter.dev/flutter/dart-core/List/removeAt.html

Upvotes: 3

Related Questions