Home > Mobile >  is there is any way to uplate a value of the object in list
is there is any way to uplate a value of the object in list

Time:08-21

I created a list like the below one and I need to change the value of the specific field

List <MODEL>list=[
{
ID:"1",
STATUS:"accept",
},
{
ID:"2",
STATUS:"reject"
}
]

i need to change the staus to "accept" for the id=2 is there is any method for this

can any one help me to achieve this

CodePudding user response:

To use a model class, it will be

class MODEL {
  final String ID;
  final String STATUS;
  MODEL({
    required this.ID,
    required this.STATUS,
  });

  MODEL copyWith({
    String? ID,
    String? STATUS,
  }) {
    return MODEL(
      ID: ID ?? this.ID,
      STATUS: STATUS ?? this.STATUS,
    );
  }

  @override
  String toString() => 'MODEL(ID: $ID, STATUS: $STATUS)';
}

void main(List<String> args) {
  List<MODEL> list = [
    MODEL(ID: "1", STATUS: "accept"),
    MODEL(ID: "2", STATUS: "reject")
  ];

  int index = list.indexWhere((element) => element.STATUS == "accept");

  list[index] = list[index].copyWith(STATUS: "Changed value");

  print(list.toString());
}

CodePudding user response:

I am not sure if you are using Model class or Map. But if you are using list of maps, you can use below code

list.forEach((element) {
    if (element['ID'] == "2") {
      element["STATUS"] = "accept";
    }
  });

If you are using List of Model then below code will help

list.forEach((element) {
    if (element.ID == "2") {
      element.STATUS = "accept";
    }
  });

This code will iterate through list and where 'ID' will be 2, it will update the 'STATUS'

  • Related