1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Flutter] Flutter StreamBuilder + AnimatedList ItemCount not updating

Discussão em 'Mobile' iniciado por Stack, Outubro 16, 2024 às 13:32.

  1. Stack

    Stack Membro Participativo

    In my chat app I have a StreamBuilder, streaming a collection of messages from Firestore, which returns an AnimatedList of messages.

    However, when a new message is added to the messages collection, rather than displaying all the messages including the most recent, the AnimatedList displays only the same number of messages as the InitialItemCount. ie the oldest message is hidden from the list.

    In the below example there are initially 3 messages in the chat when the page loads. When a 4th message is added, rather than displaying all 4 messages, instead the oldest message is removed and all the messages shift up. If a 5th is added the next oldest is removed.

    New message being added to the messages collection

    If the page loads with zero messages, then no new messages appear until the page is reloaded.

    class MessageList extends ConsumerStatefulWidget {
    const MessageList({super.key});

    @override
    ConsumerState<MessageList> createState() => _MessageListState();
    }

    class _MessageListState extends ConsumerState<MessageList> {
    late Stream<List<MessageModel>>? messageStream = ref.watch(messages).messagesStream();
    final ScrollController messageListScrollController = ScrollController();

    @override
    Widget build(BuildContext context) {
    return StreamBuilder(
    stream: messageStream,
    builder: (context, messageStreamSnapshot) {
    if (!messageStreamSnapshot.hasData) {
    return const LoadingIcon();
    }
    return AnimatedList(
    controller: messageListScrollController,
    reverse: true,
    padding: const EdgeInsets.fromLTRB(5, 100, 5, 70),
    initialItemCount: messageStreamSnapshot.data!.length,
    itemBuilder: (context, index, animation) {
    return MessageCard(
    messageData: messageStreamSnapshot.data![index],
    );
    },
    );
    },
    );
    }
    }

    ...

    Stream<List<MessageModel>>? messagesStream() {
    try {
    return _firestore
    .collection('orgs')
    [...]
    .collection('messages')
    .orderBy('timestamp', descending: true)
    .snapshots()
    .map((event) {
    List<MessageModel> messages = [];
    for (var (_, document) in event.docs.indexed) {
    messages.add(MessageModel.fromSnapshot(document));
    }
    return messages;
    });
    } catch (e) {

    }
    return null;
    }


    I'm not sure what I need to do to tell the AnimatedList that it needs to increase the ItemCount when a new message is added.

    Or do I need to completely reconsider how my chat is structured?

    Any help would be appreciated.

    Continue reading...

Compartilhe esta Página