Home > front end >  null check operator used on a null value
null check operator used on a null value

Time:12-10

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(),
        );
      },
    );
  },
);

CodePudding user response:

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;

CodePudding user response:

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();
    }
  },
),
  • Related