dart Flutter中的查找

nbysray5  于 2023-03-05  发布在  Flutter
关注(0)|答案(5)|浏览(102)

我正在学习如何在Flutter中使用查找,这是我遇到的一个例子。

void main() {
  Map<List<String>, String> lookup = {
    ['foo', 'bar']: 'foobar',
    ['baz', 'qux']: 'bazqux',
    ['hello', 'world']: 'helloworld',
  };

  List<String> key = ['foo', 'bar'];

  String? result = lookup[key];

  if (result != null) {
    print('Result: $result');
  } else {
    print('No match found for $key');
  }
}

但问题是结果是'No match found for ['foo','bar '],尽管代码是正确的。它应该返回'foobar'作为结果,但我不确定问题在哪里以及如何修复它。

oknwwptz

oknwwptz2#

问题是Dart如何比较列表的相等性。有关如何比较列表的更多信息,请参见here。但在这里不起作用。
如果你在这里使用它,你会得到这样的结果,因为它们的键是同一个对象

void main() {
    List<String> key = ['foo', 'bar'];
    Map<List<String>, String> lookup = {
      key: 'foobar',
      ['baz', 'qux']: 'bazqux',
      ['hello', 'world']: 'helloworld',
    };

    String? result = lookup[key];

  if (result != null) {
    print('Result: $result');
  } else {
    print('No match found for $key');
  }
}
332nm8kg

332nm8kg3#

问题是您试图比较新的List List<String> key = ['foo', 'bar']和现有的键['foo','bar'],由于引用不同,它们不相等,因此您需要使两个键的引用指向同一个变量key
示例:

void main() {
    List<String> key = ['foo', 'bar']; //👈 define the key on the top

    Map<List<String>, String> lookup = {
      key: 'foobar',                      // use the same key reference here
      ['baz', 'qux']: 'bazqux',
      ['hello', 'world']: 'helloworld',
    };

    String? result = lookup[key];

  if (result != null) {
    print('Result: $result');
  } else {
    print('No match found for $key');
  }
}

输出:

Result: foobar
pw9qyyiw

pw9qyyiw4#

您可以在使用IterableEquality的地方使用此函数

import 'package:collection/collection.dart';
String? getResult(Map<List<String>, String> map, List<String> key) {
    const eq = IterableEquality();
    try {
      final data = map.entries.singleWhere((element) => eq.equals(element.key,
          key)); // actually there are other function also available

      return data.value;
    } catch (e) {
      return null;
    }
  }

并测试

String? result = getResult(lookup, key);

您可以查看有关How can I compare Lists for equality in Dart?的更多信息

js81xvg6

js81xvg65#

由于声明key,这会生成一个新的对象,所以它不会被匹配。为了克服这个问题,你可以使用自定义比较函数来解决这个问题。

void main() {
  Map<List<String>, String> lookup = {
    ['foo', 'bar']: 'foobar',
    ['baz', 'qux']: 'bazqux',
    ['hello', 'world']: 'helloworld',
  };

  List<String> key = ['foo', 'bar'];

  String? result = lookup[lookup.keys.firstWhere((e)=> listEquals(e, key), orElse: () => key)];

  if (result != null) {
    print('Result: $result');
  } else {
    print('No match found for $key');
  }
}

bool listEquals<T>(List<T>? a, List<T>? b) {//This custom function which check two listed are having same content
  if (a == null) {
    return b == null;
  }
  if (b == null || a.length != b.length) {
    return false;
  }
  if (identical(a, b)) {
    return true;
  }
  for (int index = 0; index < a.length; index += 1) {
    if (a[index] != b[index]) {
      return false;
    }
  }
  return true;
}

相关问题