skip to Main Content

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


  1. use the .cast() method to safely cast the elements of your list to the desired type.

    _listener = firestoredataStream.listen((QuerySnapshot snapshot) {
      if (snapshot.docs.isNotEmpty) {
        final List<Journey> journeys = snapshot.docs.map((doc) => mapSnapshotToObject(doc)).toList();
    
        _controller.add(journeys.cast<Object>().toList());
      }
    });
    
    Login or Signup to reply.
  2. The error is telling you that the data returned from firestore is nullable, whereas your BehaviorSubject decleration only accepts non-null objects.

    Change

    final _controller = BehaviorSubject<List<Object>>();
    

    to this:

    final _controller = BehaviorSubject<List<Object?>>();
    

    When consuming your stream later in your code, you will need to handle the fact that sometimes the list can contain nullable objects.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search