Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I delete the key by knowing its values in flutter?

Tags:

I have got a map of objects:

Map<String, Transaction> _userIncome = {
    'four': Transaction(amount: 450, date: DateTime.now(), title: 'Einkommen', accountType: 'timr', notes: 'joa' , icon: Icon(Icons.today,), id: 'kololdcd', repeat: 'always'),
    'five': Transaction(amount: 60, date: DateTime.now(), title: 'Bruder', accountType: 'timr', notes: 'brother' , icon: Icon(Icons.today,), id: 'kolkfrcd', repeat: 'never'),
    'six': Transaction(amount: 60, date: DateTime.now(), title: 'Rückerstattung', accountType: 'timr', notes: 'brother' , icon: Icon(Icons.today,), id: 'kolofkfrcd', repeat: 'never'),
};

And I would like to get the key if I know the values (the values are unique), so that I can delete the the entry by its key:

_userIncome.remove(key);

I can identify the entry with the given values:

_userIncome.values
    .where((t) => t.date.difference(datte).inDays == 0 && t.id == transactionId);

But I have no clue how I get the matching key, so that I can delete the entry. Or is there a way to the delete an entry by its values?

I would love to hear some advice :)

like image 625
Georg Panteleev Avatar asked Feb 25 '20 15:02

Georg Panteleev


People also ask

How do you remove key and value from map in flutter?

Simply do: _objTable. removeWhere((key, value) => key == "propertyName");

How do you remove the key from the DART map?

remove() Function. Removes key and its associated value, if present, from the map. The function also returns the value associated with the key.


1 Answers

Simply use removeWhere to delete the entry directly. Following is the example:

 _userIncome.removeWhere((k,t) => t.date.difference(datte).inDays == 0 && t.id == transactionId);

For getting the index(or rather entry), do something as following:

final key = _userIncome.entries
      .firstWhere(
        (entry) => entry.date.difference(datte).inDays == 0 && entry.id == transactionId,
        orElse: () => null,
      )
      ?.key;
like image 194
Harsh Bhikadia Avatar answered Oct 02 '22 14:10

Harsh Bhikadia