Exception has occurred. _CastError (Null check operator used on a null value)

Issue

I have problem with this code,

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';

class HomePage extends StatefulWidget {
  const HomePage({ Key? key }) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  FirebaseFirestore firestore = FirebaseFirestore.instance;
  CollectionReference users = FirebaseFirestore.instance.collection('users');
  Stream<QuerySnapshot<Map<String, dynamic>>> collectionStream = FirebaseFirestore.instance.collection('users').snapshots();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Home Page'),
      ),
      body: StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
        stream: collectionStream,
        builder: (context, snapshot) {
          return Container(
            child: ListView.builder(
                itemCount: snapshot.data!.docs.length,
                itemBuilder: (context,  index) {
                  return ListTile(
                    title: Text(snapshot.data!.docs[index].data()['name']),
                    trailing: IconButton(
                      icon: const Icon(Icons.delete),
                      onPressed: () {
                        users.doc(snapshot.data!.docs[index].id).delete();
                      },
                    ),
                  );
                }
            ),
          );
        },
      ),
    );
  }
}

This line that makes this program error, operator (!):

snapshot.data!.docs.length
snapshot.data!.docs[index].data()['name']
snapshot.data!.docs[index].id

initially this code does not error, but when I rerun it appears : Exception has occurred. _CastError (Null check operator used on a null value). I’ve tried to fix it but still failed. Is there a way to solve this problem ?

Solution

This error means that the snapshot.data is null.

And you’re using the null-check operator on it in the line snapshot.data!.

Solution:

You need to check if the data is null and display something like a loading screen while the app waits for snapshot.data to have a value like this:

body: StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
        stream: collectionStream,
        builder: (context, snapshot) {
          if (snapshot.data == null) {
            return Center(child: CircularProgressIndicator());
          }
          return Container(
            child: ListView.builder(
                itemCount: snapshot.data.docs.length,
                itemBuilder: (context,  index) {
                  return ListTile(
                    title: Text(snapshot.data.docs[index].data()['name']),
                    trailing: IconButton(
                      icon: const Icon(Icons.delete),
                      onPressed: () {
                        users.doc(snapshot.data.docs[index].id).delete();
                      },
                    ),
                  );
                },
            ),
          );
        }
)

And since you’re checking if snapshot.data is null, you can remove the null-check operator from its usage.

So snapshot.data! in snapshot.data!.docs.length becomes snapshot.data like snapshot.data.docs.length.

Answered By – Victor Eronmosele

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published