skip to Main Content

Cant find the error generated from this code.
Null check operator used on a null value. The relevant error-causing was StreamBuilder<List<Message

class ChatList extends ConsumerWidget {
final String recieverUserId;
const ChatList({
Key? key,
required this.recieverUserId,
}) : super(key: key);

@override
Widget build(BuildContext context, WidgetRef ref) {
return StreamBuilder<List<Message>>(stream: 
ref.read(chatControllerProvider).chatStream(recieverUserId),
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting) {
      return const Loader();
    }
    return ListView.builder(
      itemCount: snapshot.data!.length,
      itemBuilder: (context, index) {
        final messageData = snapshot.data![index];
        if (messages[index]['isMe'] == true) {
          return MyMessageCard(
            message: messageData.text,
            date: messages[index]['time'].toString(),
          );
        }
        return SenderMessageCard(
          message: messageData.text,
          date: messages[index]['time'].toString(),
        );
      },
    );
  },
);

2

Answers


  1. the error is related to using BANG on a value that is not yet populated.

    use null checks where you use ‘!’.

    such as:

    snapshot.data!.length
    

    to:

    snapshot.hasdata? snapshot.data!.length: 1;
    
    Login or Signup to reply.
  2. StreamBuilder<List<Message>>(
      stream: ref.read(chatControllerProvider).chatStream(recieverUserId),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Loader();
        }
        if (snapshot.hasData) {
          return ListView.builder(
            itemCount: snapshot.data?.length ?? 0,
            itemBuilder: (context, index) {
              final messageData = snapshot.data![index];
              if (messages[index]['isMe'] == true) {
                return MyMessageCard(
                  message: messageData.text,
                  date: messages[index]['time'].toString(),
                );
              }
              return SenderMessageCard(
                message: messageData.text,
                date: messages[index]['time'].toString(),
              );
            },
          );
        } else {
          return SizedBox();
        }
      },
    ),
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search