Kozimir
Kozimir

Reputation: 83

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

Trying to compare documentID with id of Firestore DocumentReference objects in a List. And came across this strange behavior. I want to get the right object from the List. What am I doing wrong?

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

And this is an output:

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

flutter --version:

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)

flutter doctor:

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!

Upvotes: 0

Views: 510

Answers (1)

lrn
lrn

Reputation: 71763

You are using forEach to loop over the elements. The return element inside the forEach function parameter returns only from that function, not from the surrounding _resolveReferenceFromID function.

Change it to:

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

Then the return element; will return from the desired function.

See also: https://dart.dev/guides/language/effective-dart/usage#avoid-using-iterableforeach-with-a-function-literal

Upvotes: 2

Related Questions