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

Time:01-04

This is my code

@override
Widget build(BuildContext context) {
 return Scaffold(
  body:StreamBuilder(
    stream:FirebaseFirestore.instance
           .collection('chats/r7T0B5xmCSgKQFLl2uNj/messages')
           .snapshots(),
           builder:(context,streamSnapshot) {
            return ListView.builder(
             itemCount: streamSnapshot.data!.docs.length,
              itemBuilder:(ctx, index) =>
            Container(
              padding: const EdgeInsets.all(8),
               child: const Text("This Work!"),
             ),);
           } ,),
        floatingActionButton: FloatingActionButton(
          onPressed: (){},
       ),
   );
  }
}

When use null check operator on itemCount: streamSnapshot.data!.docs.length, this line got an exception, with out null check there is an error

CodePudding user response:

It will take some time to fetch data, so initially it will be null. The issue is caused by forcing not null with bang!.

You can do itemCount: streamSnapshot.data?.docs.length,

But better case,

body: StreamBuilder(
  stream: FirebaseFirestore.instance
      .collection('chats/r7T0B5xmCSgKQFLl2uNj/messages')
      .snapshots(),
  builder: (context, streamSnapshot) {
    if (streamSnapshot.hasError) {
      return Text("Error");
    }
    if (streamSnapshot.hasData) {
      return ListView.builder(
        itemCount: streamSnapshot.data?.docs.length,
        itemBuilder: (ctx, index) => Container(
          padding: const EdgeInsets.all(8),
          child: const Text("This Work!"),
        ),
      );
    }

    return CircularProgressIndicator();
  },
),

Find more about using StreamBuilder

CodePudding user response:

Check null for data length use null safety:

     StreamBuilder(
        stream: FirebaseFirestore.instance
            .collection('chats/r7T0B5xmCSgKQFLl2uNj/messages')
            .snapshots(),
        builder: (context, streamSnapshot) {
          if (streamSnapshot.hasData) {
            return ListView.builder(
              itemCount: streamSnapshot.data?.docs.length ?? 0,
              itemBuilder: (ctx, index) => Container(
                padding: const EdgeInsets.all(8),
                child: const Text("This Work!"),
              ),
            );
          } else {
            return Container();
          }
        },
      ),
  • Related