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

georg :

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 :)

Harsh Bhikadia :

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;

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=7146&siteId=1