Home > Net >  How to remove json data flutter
How to remove json data flutter

Time:02-27

My Json

[{"id":"2911","nama":"Abcd1","url":"myUrl"},{"id":"2910","nama":"Abcd2","url":"myUrl"},{"id":"2911","nama":"Abcd3","url":"myUrl"},{"id":"2549","nama":"Abcd4","url":"myUrl"}]

My Code Try

  var fromCache2 = '''$fromCache1''';
  List dataList = [];
  final jsonData = json.decode(fromCache2);
  print('Last Json : '   jsonData.toString());
  jsonData.forEach((element) {
    print('element '   element['id'].toString());
    dataList.removeWhere((e) => element['id'] == id);
    dataList.add(element);
  });
  print('New Data : '   dataList.toString());

i want to delete data where "id":"2910", but

CodePudding user response:

You could use where to filter your jsonData:

const jsonData = [
  { "id": "2909", "nama": "Abcd1", "url": "myUrl" },
  { "id": "2910", "nama": "Abcd2", "url": "myUrl" },
  { "id": "2911", "nama": "Abcd3", "url": "myUrl" },
];

void main() {
  print(jsonData.where((row) => row['id'] != '2910').toList());
}

Console log

[{id: 2909, nama: Abcd1, url: myUrl}, {id: 2911, nama: Abcd3, url: myUrl}]

CodePudding user response:

First you get index from List or JsonData. Then you can do read , delete or update.

  final index = jsonData.indexWhere((element) => element['id'] == '2549');

//remove index data

  jsonData.removeAt(index);

// update index data

  jsonData[index]['id'] = '2550';
  • Related