after setstate ui is not changing in flutter

Viewed 49

I am making a simple app and I want to show and hide reply of particular comment on button pressed of respective comment. But the UI is not changing after the state is changing. How to solve this issue ,suggest me an idea and thanks in advance. The snapchatReply list have commentId and isShown field,I want to toggle based on isShown value.

 toggleReply(String commentId){
       for(int a=0;a<snapchatReply.length;a++){
           print(snapchatReply.length);
              if(commentId==snapchatReply[a]['commentId']){
                 if(snapchatReply[a]['isShown']==false){
                setState(() {
                   snapchatReply[a]['isShown']=true;
                });
              }
              else{
                print("else");
                setState(() {
                  snapchatReply[a]['isShown']=false;
                 });
              }
              }
            }
       print(snapchatReply); 
       

  
  }

It give following outpit:

2
I/flutter ( 8112): 2
I/flutter ( 8112): [{commentId: 6312c32e842444a707b6903f, isShown: true}, {commentId: 6318257479bcbf779df08816, isShown: false}]
I/flutter ( 8112): 4
I/flutter ( 8112): else
I/flutter ( 8112): 4
I/chatty  ( 8112): uid=10154(com.example.fbclone) 1.ui identical 1 line
I/flutter ( 8112): 4
I/flutter ( 8112): [{commentId: 6312c32e842444a707b6903f, isShown: false}, {commentId: 6318257479bcbf779df08816, isShown: false}, {commentId: 6312c32e842444a707b6903f, isShown: true}, {commentId: 6318257479bcbf779df08816, isShown: false}]



    Full code:
ListView.builder(
                itemCount: widget.snapshot.comments.length,
                padding: EdgeInsets.only(bottom: 20),
                scrollDirection: Axis.vertical,
                physics: NeverScrollableScrollPhysics(),
                shrinkWrap: true,
                itemBuilder: (context, j) {
                
                  commentLike.add({"index":j,
                  "like":widget.snapshot.comments[j].commentlikes.length,
                  "commentId":widget.snapshot.comments[j].id});
                  
                  snapchatReply.add({
                    "commentId":widget.snapshot.comments[j].id,
                    "isShown":false
                    });
                
                  return SingleChildScrollView(
                    child: Container(
                      width: MediaQuery.of(context).size.width-150,
                      child: Card(
                        child: Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              IconButton(
                                  iconSize: 50,
                                  onPressed: () {},
                                  icon: CircleAvatar(
                                    radius: 80,
                                    backgroundImage: NetworkImage(
                                        widget.snapshot.comments![j].user.profile),
                                  )),
                              Column(
                                mainAxisAlignment: MainAxisAlignment.start,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Container(
                                      width: MediaQuery.of(context).size.width - 100,
                                      decoration: BoxDecoration(
                                          borderRadius: BorderRadius.circular(10),
                                          color: Colors.grey[300]),
                                      padding: EdgeInsets.all(8),
                                      child: Column(
                                          mainAxisAlignment: MainAxisAlignment.start,
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            Text(
                                              widget.snapshot.comments![j].user.name,
                                              style: TextStyle(
                                                  fontSize: 18,
                                                  color: Colors.black,
                                                  fontWeight: FontWeight.bold),
                                            ),
                                            Text(widget.snapshot.comments![j].commentText),
                                            
                                            // Text(widget.snapshot.comments![j].commentText,
                                            //     style: TextStyle(
                                            //         fontSize: 16,
                                            //         color: Colors.grey[700])),
                                          ])),
                                    Row(
                                      children: [
                                        Text(convertToAgo(
                                            widget.snapshot.comments![j].commentAt)),
                              
                                        TextButton(
                                            onPressed: () {
                                              likeComment(
                                                widget.snapshot.comments![j].id,
                                                widget.postId,
                                                );
                                            },
                                            child: Text("Like", style: myStyle)),
                                        TextButton(
                                          onPressed: () {
                                              print("isReply");
                                            setState(() {
                                              isReply=true;
                                              commentId=widget.snapshot.comments![j].id;
                                              userName=widget.snapshot.comments![j].user.name;
                                            });
                                           
                                          },
                                          child: Text("Reply", style: myStyle),
                                        ),
                                        TextButton(onPressed: (){
                                            toggleReply(widget.snapshot.comments![j].id);
                                        
                                        },
                                        child: Text("view reply"),
                                        ),
                                        if(widget.snapshot.comments![j].commentlikes!.length!=0)...[
                                          if(commentLike[j]['like']!=0)...[
                                          Text(totalLikes(commentLike[j]['like']))
                                          ]
                                        ],
                                        //  Text(totalLikes(widget.snapshot.comments![j].commentlikes!.length),
                                        //         style: myStyle),
                                      ],
                                    ),
                                    
                                    
                                     reply(snapchatReply: snapchatReply, snapshot: widget.snapshot.comments[j])
                                ],
                              ),
                            ]),
                      ),
                    ),
                  );
                
                }),

reply.dart

import 'package:flutter/material.dart';
class reply extends StatefulWidget {
  const reply({Key? key,required this.snapchatReply,required this.snapshot}) : super(key: key);
final snapshot;
final snapchatReply;
  @override
  State<reply> createState() => _replyState();
}

class _replyState extends State<reply> {
  @override
  Widget build(BuildContext context) {
    return Column(
                                 children:[
                                    for (int k = 0;k < widget.snapshot.reply!.length;k++) ...[
                                      for(int l=0;l<widget.snapchatReply.length;l++) ...[
                                         if(widget.snapchatReply[l]["commentId"]==widget.snapshot.id && widget.snapchatReply[l]["isShown"]==true) ...[
                                
                                    Row(
                                        mainAxisAlignment: MainAxisAlignment.start,
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          IconButton(
                                              iconSize: 50,
                                              onPressed: () {},
                                              icon: CircleAvatar(
                                                radius: 80,
                                                backgroundImage: NetworkImage(widget.snapshot.reply![k].user.profile),
                                              )),
                                          Column(
                                              mainAxisAlignment: MainAxisAlignment.start,
                                              crossAxisAlignment: CrossAxisAlignment.start,
                                              children: [
                                                Container(
                                                    width: MediaQuery.of(context).size.width -200,
                                                    decoration: BoxDecoration(
                                                        borderRadius:
                                                            BorderRadius.circular(10),
                                                        color: Colors.grey[300]),
                                                    padding: EdgeInsets.all(8),
                                                    child: Column(
                                                        mainAxisAlignment:
                                                            MainAxisAlignment.start,
                                                        crossAxisAlignment:
                                                            CrossAxisAlignment.start,
                                                        children: [
                                                          Text(
                                                            widget.snapshot
                                                                .reply![k].user.name,
                                                            style: TextStyle(
                                                                fontSize: 18,
                                                                color: Colors.black,
                                                                fontWeight:
                                                                    FontWeight.bold),
                                                          ),
                                                           RichText(
                                                                  text: TextSpan(
                                                                      style: TextStyle( fontSize:18,color:Colors.grey[700],fontWeight: FontWeight.bold),
                                                                      children: <TextSpan>[
                                                                        TextSpan(text:widget.snapshot.user.name + " ", style: TextStyle(color: Colors.black)),
                                                                        
                                                                        TextSpan(text:widget.snapshot.reply[k].replyText,style: TextStyle(fontWeight: FontWeight.normal) ),
                                                                      ],
                                                                  ),
                                                                ),
                                                        ])),
                                                         
                                                               ])
                                                  ])
                                    ]
                                      
                                      ]
                                      
                                      
                                      ]
                                    ],
      
    );
  }
}     
1 Answers

You can not use snapchatReply[a]['isShown'] to change variable inside map inside the list, you should pass new variable to it, try this:

toggleReply(String commentId) {
    for (int a = 0; a < snapchatReply.length; a++) {
      print(snapchatReply.length);
      if (commentId == snapchatReply[a]['commentId']) {
        if (snapchatReply[a]['isShown'] == false) {
          setState(() {
            snapchatReply[a] = {
              'commentId': snapchatReply[a]['commentId'],
              'isShown': true
            };
          });
        } else {
          print("else");
          setState(() {
            snapchatReply[a] = {
              'commentId': snapchatReply[a]['commentId'],
              'isShown': false
            };
          });
        }
      }
    }
  }

your main issue is every time you call setstate this:

snapchatReply.add({
                "commentId":widget.snapshot.comments[j].id,
                "isShown":false
                });

will call, so this is cause doubling you list length every time, what you need to do is, rest you list before it. so try call snapchatReply = []; before returning your ListView.builder.

Related