While fetching the list of data from Firebase Firestore using Stream Builder in the StreamSubcription listener fetching it as QuerySnapshot and is not able to cast to a List.
late StreamSubcription _listener;
final _controller = BehaviorSubject<List<Object>>();
Stream<List<Journey>> get getList => _controller.stream.distinct();
Stream<QuerySnapshot<Map<dynamic, dynamic>>> firestoredataStream =
FirebaseFirestore.instance
.collection('journeys')
.where('userID', isEqualTo: _user.email)
.snapshots();
_listener = firestoredataStream.listen((QuerySnapshot snapshot) {
if (snapshot.docs.isNotEmpty) {
_controller.add(snapshot.docs.map((doc) => mapSnapshotToObject(doc)).toList() as List<Object>);
}
});
Even it gives an error in debug mode for Typecast.
please rectify this error.
2
Answers
use the
.cast()
method to safely cast the elements of your list to the desired type.The error is telling you that the data returned from firestore is nullable, whereas your BehaviorSubject decleration only accepts non-null objects.
Change
to this:
When consuming your stream later in your code, you will need to handle the fact that sometimes the list can contain nullable objects.