Chidinma Ekenne
Chidinma Ekenne

Reputation: 121

Updating single item on a Listview.builder widget in Flutter

so I have a list of users that is in a Listview.builder widget but my issue is that when I try to update one item on the list all the other items update as well. I have a button that shows "Add friend" when I click on the button the message should change to "Invited", I have a string variable that holds the message so when I click on the button the string is updated from "Add friend" to "Invited", now when I click on button all the other button values change as well.

Here is my code:

class Friends extends StatefulWidget{
  _FriendsState createState() => _FriendsState();
}

class _FriendsState extends State<Friends>{
  List<String> nameList = [];
  String btnText;
  @override
  Widget build(BuildContext context) {
    bool showFriendList = false;

    return Scaffold(

        appBar: AppBar(
        title: Text('Friends'),
          actions: <Widget>[
            IconButton(
              onPressed: (){

              },
              icon: Icon(Icons.check, color: Colors.white,),
            )
          ],
        ),
      body:
          Padding(
            padding: EdgeInsets.all(10),
            child: ListView(
              children: <Widget>[
                showFriendList? Column(
                  children: <Widget>[
                    Text('Find friends to add. Once they accept you can invite them to your challenge.', style: TextStyle(fontWeight: FontWeight.w500, fontSize: 16),),
                    SizedBox(height: 45,),
                    Container(
                      width: MediaQuery.of(context).size.width,
                      child:  RaisedButton(
                        child: Text('GO AND FIND FRIENDS', style: TextStyle(fontWeight: FontWeight.w500, fontSize: 14, color: Colors.white)),
                        onPressed: (){
                          setState(() {
                            showFriendList != showFriendList;
                          });
                        },
                        color: Theme.of(context).accentColor,
                        shape: RoundedRectangleBorder(side: BorderSide(color: Theme.of(context).accentColor),borderRadius: BorderRadius.circular(14)),
                      ),
                    )
                  ],
                ): Container(

                  height: MediaQuery.of(context).size.height,
                  child:friends(context) ,
                )
              ],
            ) ,
          )

    );



  }
  Widget friends(BuildContext context){

    return
      ListView(
        children: <Widget>[
          Container(
            margin: EdgeInsets.all(8),
            padding: EdgeInsets.all(8),
            decoration: BoxDecoration(
                color: Colors.white
            ),
            child: TextField(
              decoration:InputDecoration(
                hintText: 'Enter User\'s name',
                border: InputBorder.none,),

            ),
          ),

     /*     noRequest== true? SizedBox(height: 0,):friendRequest(context),
          noRequest== true? SizedBox(height: 0,): Container(
            margin: EdgeInsets.all(10),
            height: 60,

            child: Column(mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment:CrossAxisAlignment.start,
              children: <Widget>[Text('Your friends', style: TextStyle(fontSize: 16, color: Theme.of(context).textSelectionColor,)) ],),
          ),*/
          Container(
            height: 0.5,
            color: Colors.grey,
          ),
          ListView.builder(
              shrinkWrap: true,
              itemCount: users.length,
              itemBuilder: (BuildContext context, int index){
                return
                  Container(
                    padding: EdgeInsets.only(left: 6),
                    height:80 ,
                    child:
                    Column(
                      children: <Widget>[

                        Row(
                          children: <Widget>[
                            users[index].profileUrl != null? CircleAvatar(child: Image.asset(users[index].profileUrl),): Container(

                              width: 50,
                              height: 50,
                              decoration: BoxDecoration(
                                  color: Colors.white70,
                                  shape: BoxShape.circle,
                                  image: DecorationImage(
                                      image:AssetImage('assets/plus.png') //NetworkImage(renderUrl ??'assets/img.png')
                                  )
                              ),

                            ),

                            SizedBox(width: 30,),
                            Expanded(
                              flex: 1,
                              child:
                              Container(

                                  child:
                                  Row(
                                    children: <Widget>[

                                      Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: <Widget>[
                                          SizedBox(height: 12,),
                                          users[index].fullName != null? Text( users[index].fullName, style: TextStyle(fontSize: 18)): Text('Anjelika Thompson', style: TextStyle(fontSize: 18),),
                                          SizedBox(height: 12,),

                                          Row(
                                            //crossAxisAlignment: CrossAxisAlignment.start,
                                            // mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                              children: <Widget>[
                                                Container(child: Icon(Icons.location_on),alignment: Alignment.topLeft,),
                                                SizedBox(width: 10,),
                                                users[index].distance_KM.toString() != null ? Text( users[index].distance_KM.toString()):Text('48.7 km')

                                              ]),

                                        ],
                                      ),

                                    ],
                                  )
                              ),
                            ),
                            SizedBox(width: 0,),
                            //Icon(Icons.check,color: Colors.red,size: 40,)

                            FlatButton(
                              child: Text(btnText==null? 'ADD FRIEND': btnText, style: TextStyle(color: Color(0xff7667e5)),),
                              onPressed: () {
                                nameList.add(users[index].fullName);

                                setState(() {

                                  btnText = 'INVITED';


                                });

                              },
                            )
                          ],
                        ),
                        Container(
                          height: 0.5,
                          color: Colors.grey,
                        )
                      ],
                    ) ,

                  );
              }
            // final item = feeds[index];

          )
        ],
      );

  }
}

From my class, I have a string value called "btnText" that I use to set the new value. but at the moment once I click on one button to change from "Add friend" to "Invited" all other button Text in the listview change as well. Please I need help figuring out what is the problem

Upvotes: 3

Views: 6150

Answers (2)

Cantivan
Cantivan

Reputation: 1

Method

inviteButtonStateFunction(index){

  for (var e in invitedPeopleListIndex) {

    if(e == index){
      return Text("Invited");
    }

  }
  
  return Text("Invite");
}

Usage

child: TextButton(
    onPressed: () {

      if(invitedPeopleListIndex.contains(index)){

        invitedPeopleListIndex.remove(index);

      }else{

        invitedPeopleListIndex.add(index);

      }

      print(invitedPeopleListIndex);
      print(invitedPeopleList);

    },
    child: inviteButtonStateFunction(index), // Show the text here
  )

Upvotes: -1

Pro
Pro

Reputation: 3003

@Chidinma, you can add a check to see if user is in your nameList,

FlatButton(
  child: Text(btnText==null || !nameList.contains(users[index].fullName) ? 'ADD FRIEND': btnText, style: TextStyle(color: Color(0xff7667e5)),),
  onPressed: () {
    nameList.add(users[index].fullName);
    setState(() {
      btnText = 'INVITED';
    });
  ................

Test

This is just to give you an idea. A better solution would be to create a selected column in users table and save selected state as bool value. If you don't have database then i'd recommend creating indexList like nameList and save the index of invited friends and check to see if index is in the indexList like i've done with the nameList instead.

Upvotes: 2

Related Questions