Home > front end >  How remove the specific value from map in dart?
How remove the specific value from map in dart?

Time:01-09

I am Beginner in flutter , learning map concept. I am confusing map methods. I want 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 a specific value. for example, I want to delete the "name" from "student1". How to do that, Please do ur needful

CodePudding user response:

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

CodePudding user response:

To delete a specific value from a Map in Flutter, you can use the remove method. This method takes the key of the key-value pair you want to remove as an argument and removes the corresponding key-value pair from the Map.

For example, to remove the "name" field from the "student1" record in the Map you provided, you can use the following code:

data["student1"].remove("name");

This will remove the "name" field from the "student1" record, leaving the other fields in the record intact.

If you want to remove the entire "student1" record from the Map, you can use the remove method on the Map itself, like this:

data.remove("student1");

This will remove the entire "student1" record, including all of its fields, from the Map.

CodePudding user response:

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}}
  • Related