在Flutter中更新ListView.builder小部件上的单个项目

3
所以我有一个用户列表,它在Listview.builder小部件中,但我的问题是,当我尝试更新列表上的一个项目时,所有其他项目也会更新。 我有一个按钮,当我点击按钮时,它显示“添加朋友”,消息应该更改为“已邀请”,我有一个字符串变量来保存消息,所以当我点击按钮时,字符串从“添加朋友”更新为“已邀请”,现在当我点击按钮时,所有其他按钮值也会更改。
以下是我的代码:
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];

          )
        ],
      );

  }
}

我有一个名为“btnText”的字符串值,用于设置新值。但是目前,一旦我点击一个按钮将其从“添加好友”更改为“已邀请”,列表视图中所有其他按钮的文本也会更改。 请帮助我找出问题所在。

2个回答

2

@Chidinma,你可以添加一个检查来确定用户是否在你的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';
    });
  ................

测试

这只是为了给你一个想法。更好的解决方案是在users表中创建一个selected列,并将selected状态保存为布尔值。如果您没有数据库,那么我建议创建类似nameListindexList并保存已邀请朋友的索引,然后检查索引是否在indexList中,就像我对nameList所做的那样。


1
是的,但现在这应该可以正常工作了,保存在namelist列表中的值将传递到另一个页面。非常感谢。 - Chidinma Ekenne

-1

方法

inviteButtonStateFunction(index){

  for (var e in invitedPeopleListIndex) {

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

  }
  
  return Text("Invite");
}

使用方法

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
  )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接