Group chat flutter screen rebuilding on small changes in an single message?? How to optimize it

62 Views Asked by At

I am trying to make an community app but the main problem is in community chat screen my whole widget is again rebuilding on an small change in a single message in an realtime database

Here is my chat screen

body: StreamBuilder(
  stream: messageStream,
  builder: ((context, snapshot) {
    if (snapshot.connectionState == ConnectionState.done ||
        snapshot.connectionState == ConnectionState.active) {
      if (!snapshot.hasData) {
        return Center(child: CircularProgressIndicator());
      } else {
        List<dynamic> messages =
            snapshot.data!.snapshot.children.toList();
          messages.forEach((element) {
          print(element.value['from']);
          })   ;
        // messages.sort()    
        int n = messages.length;
        return ListView.builder(
            // shrinkWrap: true,
            // primary: false,
            cacheExtent: double.maxFinite,
            reverse: true,
            keyboardDismissBehavior:
                ScrollViewKeyboardDismissBehavior.onDrag,
            itemCount: messages.length,
            itemBuilder: ((context, index) {
              // return Text("HI");
              print(messages[index]);
              return MessageCard(
                key: ValueKey(messages[index]),
                index: n - 1 - index,
                messages: messages,
              );
            }));
        
      }
    } else {
      return Center(child: CircularProgressIndicator());
    }
  }),
),

My message card is an simple statelesswidget

1

There are 1 best solutions below

2
Syed Abdul Basit On

I don't think that any other optimization solution but as far as my knowledge for performance optimization, consider using Slivers instead of ListView. Additionally, since you are using ValueKey, Flutter can efficiently identify each message widget individually.