Juan Casas
Juan Casas

Reputation: 122

Orderby not working when displaying records from firebase

I am trying to display a list according to when it was created. for some weird reason, the list is getting confused or something, because its displaying messages out of order.

the chat appears to be sorting alphabetically sometimes, not sure why. the expected behavior should be that the messages are displayed like they are on phones

I added a video with how the messages are being displayed https://youtu.be/w00cNi_uEa0


class Messages extends StatelessWidget {
  final currentUser = AuthService.firebase().currentUser!;
  User? _currentUser = FirebaseAuth.instance.currentUser;
  String chatId;
  Messages({required this.chatId});

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: FirebaseFirestore.instance
          .collection('chat messages')
          .where('chatId', isEqualTo: chatId)
          .orderBy(
            'createdAt',
            descending: true,
          )
          .snapshots(),
      builder: (ctx, chatSnapshot) {
        if (chatSnapshot.connectionState == ConnectionState.waiting) {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
        final chatDocs = chatSnapshot.data?.docs;
        // final isMe = chatDocs?[index]['userId'] == currentUser;

        return ListView.builder(
          // shrinkWrap: true,
          reverse: true,
          itemCount: chatDocs?.length,
          itemBuilder: (ctx, index) => MessageBubble(
            message: chatDocs?[index]['text'],
            isMe: chatDocs?[index]['userId'] == currentUser.id,
            key: ValueKey(chatDocs?[index].id),
            // userName: chatDocs?[index]['userId'],
          ),
        );
      },
    );
  }
}
``

Upvotes: 0

Views: 167

Answers (0)

Related Questions