skip to Main Content

I am Beginner in flutter, learning map concept. I am confusing map methods. How to delete a specific value from a map?

for example:

Map data = {
  "studet1": {"name": "ajk", "age": "22", "place": "delhi"},
  "studet2": {"name": "akmal", "age": "25", "place": "up"}
};

I want to delete the "name" from "student1".

2

Answers


  1. data is a nested map, which means that it has another map within the key of student1.

    You can use the .remove method to remove a key within a map:

    Removes key and its associated value, if present, from the map.

    void main() {
      Map data ={
        "student1":{
          "name" : "ajk",
          "age":"22",
          "place":"delhi"
    
        },
        "student2":{
          "name" : "akmal",
          "age":"25",
          "place":"up"
    
        }
      };
      
      data['student1'].remove('name');
      print(data);
    }
    
    

    Prints:

    {student1: {age: 22, place: delhi}, student2: {name: akmal, age: 25, place: up}}
    
    Login or Signup to reply.
  2. If you want to remove only student1 name

    Just use data['student1'].remove('name');

    Or if you want to remove all students name use the bleow method

       Map data = {
          "studet1": {"name": "ajk", "age": "22", "place": "delhi"},
          "studet2": {"name": "akmal", "age": "25", "place": "up"}
        };
        for (int i = 0; i <= data.length - 1; i++) {
          data[data.keys.elementAt(i)].remove('name');
        }
    

    The output will be

    {student1: {age: 22, place: delhi}, student2: {age: 25, place: up}}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search