【问题标题】:Comparing two strings in Flutter web / Comparing documentID's of two Cloud Firestore objects比较 Flutter web 中的两个字符串/比较两个 Cloud Firestore 对象的 documentID
【发布时间】:2020-12-17 01:35:47
【问题描述】:

尝试将 documentID 与 List 中 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!

【问题讨论】:

    标签: string dart google-cloud-firestore string-comparison flutter-web


    【解决方案1】:

    您正在使用forEach 循环遍历元素。 forEach 函数参数中的 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;将从所需的函数返回。

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

    【讨论】:

    • 如果答案有帮助,请考虑接受它以帮助社区直观地看到答案解决了您的问题。
    • 这个答案解决了我遇到的问题。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-05
    • 2017-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多