I am working on an Exercises app. I am using FIREBASE with a StreamBuilder to retrieve an "exercise id" that has been favorited in my app. This is working fine and I get the correct Id. I then pass it to a simple method to retrieve the actual "exercise" so that I can display it. This method passes through a List of exercises, checking if the exercise id, is found, and then I want it to return the exercise. However I am always getting null returned. I can't figure out why this is.
I'd really appreciate some help, as very stuck with it right now.
Here below is my code:
This is the method:
Exercise getExerciseByID(String exerciseId) {
_exercises.forEach((exercise) {
print('COMPARE1: ${exercise.id} AND $exerciseId');
if (exercise.id == exerciseId) {
print('COMPARE2: ${exercise.id} AND ${exerciseId}');
return exercise;
}
});
}
Note that the two print statements both print and show matching id's
And here is the Build with StreamBuilder etc..
return Scaffold(
body: StreamBuilder(
stream: FirebaseFirestore.instance
.collection('favorites')
.doc('${_firebaseAuth.currentUser.uid}')
.collection('userFavorites')
.snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData)
return Center(
child: CircularProgressIndicator(),
);
return ListView.builder(
itemCount: snapshot.data.docs.length,
itemBuilder: (context, index) {
//TODO: GET EXERCISE FOR DOC
String _exerciseId = snapshot.data.docs[index].id;
_exercise = getExerciseByID(_exerciseId);
//TODO: DISPLAY CARD
print("Retrieved Exercise: $_exercise");
return Center(child: Text(""));
},
);
},
// padding: EdgeInsets.only(left: sideMargin),
// },
),
);
Note: the print statement: print("Retrieved Exercise: $_exercise"); is where I am always finding the NULL.
Many thanks for any assistance.
CodePudding user response:
change this
Exercise getExerciseByID(String exerciseId) {
_exercises.forEach((exercise) {
print('COMPARE1: ${exercise.id} AND $exerciseId');
if (exercise.id == exerciseId) {
print('COMPARE2: ${exercise.id} AND ${exerciseId}');
return exercise;
}
});
}
to this
Exercise getExerciseByID(String exerciseId) {
Exercise returningExercise;
_exercises.forEach((exercise) {
print('COMPARE1: ${exercise.id} AND $exerciseId');
if (exercise.id == exerciseId) {
print('COMPARE2: ${exercise.id} AND ${exerciseId}');
returningExercise = exercise;
}
});
return returningExercise;
}
You are returning inside ForEach Statement. This doesn't return to your function.
put return statement outside ForEach statement.
Note: This solution is not best. But you now know whats going wrong.