Sharki
Sharki

Reputation: 424

Dart, I can't return anything inside of a foreach

So, as the title says, I can't return anything inside of a foreach in this function. It is not a problem of the conditional because I have tried it and it works, I can enter in it, I can even print a text, but I cannot return anything, which is weird, maybe forEach in dart works different than I know?

Future<String> getEnrollment(idU) async {
  final querySnapshot =
      await FirebaseFirestore.instance.collection('Enrollment').get();

  querySnapshot.docs.forEach((doc) {
    if (doc['infoCar']['idUser'] == idU) {
      return doc.id; // I can't return this one.
    }
  });

  return null;
}

Upvotes: 1

Views: 563

Answers (2)

Randal Schwartz
Randal Schwartz

Reputation: 44056

Replace your iterable.forEach... with for (e in iterable) { ... if ([something about e]) { return [something] } }

That'll work because the return now means the enclosing subroutine.

Upvotes: 0

This is not a problem with Dart. You are facing this problem because the function inside of forEach is a callback function. So, when your return inside that function, you are returning doc.id from that function, instead of getEnrollment() function. You can see the same behavior in other languages that support callbacks e.g JavaScript.

However, you can solve your problem using firstWhere() instead.

 Future<String> getEnrollment(idU) async {
    final querySnapshot =
        await FirebaseFirestore.instance.collection('Enrollment').get();

    final enrollment = querySnapshot.docs.firstWhere(
      (doc) => doc['infoCar']['idUser'] == idU,
      orElse: () => null,
    );

    if (enrollment == null) return null;
    return enrollment.id;
  }

Note: orElse runs when the firstWhere doesn't return true for any item in the list. Here we are returning null in that case.

Upvotes: 2

Related Questions