I have a Bank class which contains exchange rates. I can add items into the map but cannot retrieve the value with the same key I used to put inside the map.
class Bank {
Map<Map<String, String>, double> _exchangeRates = Map();
void addExchangeRate(String from, String to, double i) {
_exchangeRates[{from: to}] = i;
}
double getExchangeRate(String from, String to) {
return _exchangeRates[{from, to}];
}
}
void main(){
Bank bank = Bank();
bank.addExchangeRate("USD", "CHF", 2);
bank.addExchangeRate("INR", "USD", 1 / 60);
bank.addExchangeRate("INR", "NRS", 160/100);
print(bank.getExchangeRate("USD","CHF"));
print(bank.getExchangeRate("INR","USD"));
print(bank.getExchangeRate("INR","NRS"));
}
Output :
null
null
null
That's because you are using objects as Keys, but when you try to retrieve the values you are creating new objects, so the result value is null.
I would use String as a Key composed by from and to values, like this:
class Bank {
Map<String, double> _exchangeRates = Map();
void addExchangeRate(String from, String to, double i) {
_exchangeRates["$from$to"] = i;
}
double getExchangeRate(String from, String to) {
return _exchangeRates["$from$to"];
}
}
void main() {
Bank bank = Bank();
bank.addExchangeRate("USD", "CHF", 2);
bank.addExchangeRate("INR", "USD", 1 / 60);
bank.addExchangeRate("INR", "NRS", 160/100);
print(bank.getExchangeRate("USD","CHF"));
print(bank.getExchangeRate("INR","USD"));
print(bank.getExchangeRate("INR","NRS"));
}
The problem is, in Dart everything is an object and the Map you are seeking for is not same Object the Map you are searching with. So you are getting null. You need advanced methods for this.
This is the solution:
import 'package:collection/collection.dart';
class Bank {
Function equals = const MapEquality().equals;
Map<Map<String, String>, double> _exchangeRates = Map();
void addExchangeRate(String from, String to, double i) {
_exchangeRates[{from: to}] = i;
}
double getExchangeRate(String from, String to) {
return _exchangeRates[_exchangeRates.keys.firstWhere((entry){
return equals(entry, {from : to});
})];
}
}
void main() {
Bank bank = Bank();
bank.addExchangeRate('USD', 'CHF', 2);
bank.addExchangeRate('INR', 'USD', 1 / 60);
bank.addExchangeRate('INR', 'NRS', 160 / 100);
print(bank.getExchangeRate('USD', 'CHF'));
print(bank.getExchangeRate('INR', 'USD'));
print(bank.getExchangeRate('INR', 'NRS'));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With