【问题标题】:Updating single item on a Listview.builder widget in Flutter在 Flutter 中更新 Listview.builder 小部件上的单个项目
【发布时间】:2021-08-13 03:35:54
【问题描述】:

所以我有一个 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”的字符串值,用于设置新值。但是目前,一旦我单击一个按钮以从“添加朋友”更改为“已邀请”,列表视图中的所有其他按钮文本也会更改。 请帮助我找出问题所在

【问题讨论】:

    标签: flutter


    【解决方案1】:

    @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 状态保存为布尔值。如果您没有数据库,那么我建议您创建 indexListnameList 并保存邀请朋友的索引并检查索引是否在 indexList 中,就像我对 nameList 所做的那样。

    【讨论】:

    • 是的,但现在这应该可以正常工作,保存在名称列表列表中的值将被传递到不同的页面。非常感谢
    【解决方案2】:

    方法

    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
      )
    

    【讨论】:

      猜你喜欢
      • 2021-02-08
      • 2020-05-24
      • 1970-01-01
      • 1970-01-01
      • 2021-12-26
      • 2022-01-23
      • 2018-09-26
      • 2021-01-19
      • 2021-03-17
      相关资源
      最近更新 更多