0

I know this problem is related with dart null safety but i am unable to fix this issue as i am getting this 'Null check operator used on a null value Flutter' error.Please help me to fix this

my code is:

class _ListStudentPageState extends State<ListStudentPage> {
  final Stream<QuerySnapshot> studentStream =
  FirebaseFirestore.instance.collection('students').snapshots();
  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: studentStream,
      builder:(BuildContext context , AsyncSnapshot<QuerySnapshot> snapshot){
      if(snapshot.hasError)
        {
          print('something went wrong');
        }
      if(snapshot.connectionState == ConnectionState.waiting)
        {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
       final List storeDocs =[];
      snapshot.data!.docs.map((DocumentSnapshot document){
        Map a = document.data() as Map<String , dynamic>;
        storeDocs.add((a));
        a['id'] = document.id;
      }).toList();
Saad Ebad
  • 206
  • 5
  • 16
  • Check the debugger, `snapshot.data` is probably null. – Raul Sauco Dec 14 '21 at 19:55
  • 1
    If snapshot has error the code following the next if statement will still execute since you are not returning or throwing. Maybe `snapshot.hasError` is true, then `snapshot.data` is null and you are getting the error. – Raul Sauco Dec 14 '21 at 19:57

1 Answers1

0

I would try this:

      final List storeDocs =[];
      if(snapshot.data=null){
      snapshot.data!.docs.map((DocumentSnapshot document){
        Map a = document.data() as Map<String , dynamic>;
        storeDocs.add((a));
        a['id'] = document.id;
      }).toList();
}

or in prettier way

      final List storeDocs =[];
      snapshot.data?.docs??[].map((DocumentSnapshot document){
        Map a = document.data() as Map<String , dynamic>;
        storeDocs.add((a));
        a['id'] = document.id;
      }).toList();
david dagan
  • 141
  • 5