飞镖图:无法使用添加时使用的相同键从中检索项目

时间:2019-07-19 06:16:27

标签: flutter dart

我有一个Bank class,其中包含exchange rates。我可以在地图中添加项目,但无法检索,其值与我过去在地图中放置的键相同。

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"));
}

输出:

null
null
null

3 个答案:

答案 0 :(得分:2)

那是因为您将对象用作键,但是当您尝试检索值时,您正在创建新对象,因此结果值为null。

我会使用String作为由fromto值组成的键,如下所示:

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"));
}

答案 1 :(得分:2)

问题在于,在Dart中,所有事物都是一个对象,而您要搜索的Map与搜索时的Object不同。因此,您将获得null。您需要为此使用高级方法。

这是解决方案:

Map

答案 2 :(得分:2)

作为第三种选择,我建议使用具有非标准相等性的Map。这就是软件包MapEquality中的collection的用途之一。

import 'package:collection/collection.dart';

class Bank {
  static const _me = MapEquality();
  Map<Map<String, String>, double> _exchangeRates = 
      Map(equals: _me.equals, hashCode: _me.hash);

  void addExchangeRate(String from, String to, double i) {
    _exchangeRates[{from: to}] = i;
  }

  double getExchangeRate(String from, String to) =>
      _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'));
}

这使查找更为有效,因为它执行基于哈希的查找,而不是线性搜索。 每次查找仍需要创建新地图。

似乎这里的“地图”实际上只是一个Map是仅用于存储一对的高成本抽象,它没有自然的等式。建议使用"$from$to"作为密钥比使用密钥更好。如果以后需要分隔值,则还可以使用包含两个字符串的新类,并使用等号和哈希码进行匹配,例如:

class _StringPair {
  final String first;
  final String second;
  _StringPair(this.first, this.second);
  int get hashCode => (first.hashCode * 37 + second.hashCode * 17) & 0x3FFFFFFF;
  bool operator==(Object other) => 
      other is _StringPair && first == other.first && second == other.second;
}

然后使用StringPair(from,to)作为键,而不是{from: to}