比较 Flutter web 中的两个字符串/比较两个 Cloud Firestore 对象的文档 ID

Comparing two strings in Flutter web / Comparing documentID's of two Cloud Firestore objects

正在尝试将文档 ID 与列表中 Firestore DocumentReference 对象的 ID 进行比较。并遇到了这种奇怪的行为。我想从列表中获取正确的对象。我做错了什么?

DocumentReference _resolveReferenceFromID(
      List<DocumentReference> references, String documentID) {
    references.forEach((element) {
      print('element id: ${element.documentID}');
      print('document id: $documentID');
      if (element.documentID == documentID) {
        return element;
      }
    });
    print('something is wrong here');
    return null;
  }

这是一个输出:

element id: W24buSwq7cYOahJz6Gdq
document id: W24buSwq7cYOahJz6Gdq
element id: cBOIXvebYYIpox5cAcct
document id: W24buSwq7cYOahJz6Gdq
something is wrong here

扑动——版本:

Flutter 1.22.0-2.0.pre.36 • channel master • https://github.com/flutter/flutter.git
Framework • revision d30e36ba8c (6 days ago) • 2020-08-21 22:36:03 -0400
Engine • revision d495da20d0
Tools • Dart 2.10.0 (build 2.10.0-49.0.dev)

扑博士:

Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel master, 1.22.0-2.0.pre.36, on Microsoft Windows [Version 10.0.18362.1016], locale en-US)

[√] Android toolchain - develop for Android devices (Android SDK version 30.0.1)
[√] Chrome - develop for the web
[√] Android Studio (version 4.0)
[√] VS Code (version 1.48.2)
[√] Connected device (3 available)

• No issues found!

您正在使用 forEach 循环元素。 forEach 函数参数 return 中的 return element 仅来自该函数,而不来自周围的 _resolveReferenceFromID 函数。

改为:

DocumentReference _resolveReferenceFromID(
      List<DocumentReference> references, String documentID) {
    for (var element in references) {
      print('element id: ${element.documentID}');
      print('document id: $documentID');
      if (element.documentID == documentID) {
        return element;
      }
    }
    print('something is wrong here');
    return null;
  }

然后 return element; 将从所需函数中 return。

另请参阅:https://dart.dev/guides/language/effective-dart/usage#avoid-using-iterableforeach-with-a-function-literal