我单击的那个特定盒子的flutter更改setstateicon

发布于 2025-02-13 13:00:41 字数 7873 浏览 1 评论 0原文

我想在点击的循环中更改该特定盒子的图标。 我有两个具有ONTAP功能的图标。然后,单击用户添加到最爱列表以及响应ID成功并添加到最爱时,则更改了框FAV图标。但是在我的情况下,成功响应后,它更改了循环中所有盒子的图标。 因此,请帮助我如何添加图标/或最爱SVG图像的索引。

这是我的代码:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:mindmatch/utils/widget_functions.dart';
import 'package:mindmatch/screens/Persondetail.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:mindmatch/utils/Auth.dart';

class Sent extends StatefulWidget {

Sent({Key? key}) : super(key: key);

@override
_Sent createState() => _Sent();
}



class _Sent extends State<Sent>{

var UsrID = Auth.prefs?.getString('usrid');
var data;
var usrpic = "";
var user = "";
var usridf = "";
var favicon = "assets/images/Fav_1.svg";

@override
void initState() {
 super.initState();
 getData();
}

getData() async{
 //var res = await http.get(Uri(host: url));
 var res = await http.get(Uri.https('www.*******.net', '/index.php',{'act':'sentmatches'}));
 data = jsonDecode(res.body);
 print(data);
 setState(() {});
 print(res.body);
}


@override
Widget build(BuildContext context){
 final Size size = MediaQuery.of(context).size;
 final ThemeData themeData = Theme.of(context);
 final double padding = 25;
 final sidePadding = EdgeInsets.symmetric(horizontal: padding);
 return
  data != null? Expanded(
        child: Padding(
          padding: sidePadding,
          child:  GridView.builder(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              //maxCrossAxisExtent: 200,
                crossAxisCount: 2,
                crossAxisSpacing: 20,
                mainAxisSpacing: 20,
              childAspectRatio: 0.75,
            ),
            itemCount: data.length,
            itemBuilder: (context, index) {
              return InkWell(
                onTap: () {
                  Auth.prefs?.setString('profid', data[index]['id']);

                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => Persondetail()),
                  );
                },
                child:  Container(
                  width: MediaQuery.of(context).size.width,
                  height: MediaQuery.of(context).size.height,
                  child: Stack(
                    children: [
                      Positioned(
                        top: 5,
                        right: 5,
                        child: InkWell(
                          onTap: () async{
                            usridf = data[index]['id'];
                            user = '${UsrID}';

                            final body = null;
                            final url = Uri.https('www.*******.net', '/index.php',{'act':'addfav','usridf': usridf, 'user': user});
                            final response = await http.post(
                                url,
                                headers: {'Content-Type': 'application/json'},
                                body: body
                            );
                            print(url);
                            int statusCode = response.statusCode;
                            //var responseBody = json.decode(response.body);
                            Map<String, dynamic> responseBody = jsonDecode(response.body);
                            setState(() {});

                            var list = responseBody['error'];
                            var stringList = list.join("\n");
                            print(stringList); //Prints "in new line"

                            var statusRes = responseBody['status'];
                            //var UserPhone = responseBody['phone'];
                            //var UserID = responseBody['usrid'];
                            if(statusRes == 'add success'){
                              print('success: '+statusRes);
                            } else if(statusRes == 'remove success') {
                              print('success: '+statusRes);
                            } else {
                              print('error: '+statusRes);
                            }


                            setState(() {
                              favicon = "assets/images/Fav_2.svg";
                            });
                          },
                          child: SvgPicture.asset(
                            width: 30,
                            favicon,
                            height: 30,
                          ),
                        ),
                      ),
                      Positioned(
                        bottom: 5,
                        left: 10,
                        right: 5,
                        child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children:[
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  //Row(
                                  //mainAxisAlignment: MainAxisAlignment.start,
                                  //children: <Widget>[
                                  SizedBox(width: 5.0),
                                  Text(
                                    data[index]['fulname'],
                                    style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 15
                                    ),
                                  ),
                                  addVerticalSpace(0),
                                  Text(
                                    'Dieppe, Canada.',
                                    style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 10
                                    ),
                                  )
                                  //],
                                  //),
                                ],
                              ),
                              Column(
                                //textDirection: TextDirection.rtl,
                                children: [
                                  CircleAvatar(
                                    radius: 18,
                                    backgroundColor: Color(0xff8f9df2),
                                    child: IconButton(
                                      icon: SvgPicture.asset(
                                        'assets/images/f_chat.svg',
                                        width: 18,
                                        height: 18,
                                      ),
                                      onPressed: () {},
                                    ),
                                  ),

                                ],
                              ),
                            ]
                        ),
                      ),
                    ],
                  ),

                  decoration: BoxDecoration(
                    color: Colors.black,
                    borderRadius: BorderRadius.circular(10),
                    image: DecorationImage(
                      fit: BoxFit.cover,
                      image: NetworkImage("https://www.*******.net/files/profile/${data[index]['profimage']}"),
                      colorFilter: ColorFilter.mode(Colors.black.withOpacity(0.3), BlendMode.darken),
                    ),
                  ),
                ),
              );
            },
          )
        )
    ): const Center(
    child: CircularProgressIndicator(),
  );
 }
 }

请帮助我如何执行此操作,并更改我单击的该框的SVG图像/图标。

I want to change icon of that specific box in a loop that I click.
I have two icons that have onTap functionality. and on click user add to fav list and when the response id success and add to fav then the box fav icon changed. but in my case after the success response, it changed the icon of all boxes in the loop.
So please help with how I add indexing for an icon/or fav SVG image.

here is my code:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:mindmatch/utils/widget_functions.dart';
import 'package:mindmatch/screens/Persondetail.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:mindmatch/utils/Auth.dart';

class Sent extends StatefulWidget {

Sent({Key? key}) : super(key: key);

@override
_Sent createState() => _Sent();
}



class _Sent extends State<Sent>{

var UsrID = Auth.prefs?.getString('usrid');
var data;
var usrpic = "";
var user = "";
var usridf = "";
var favicon = "assets/images/Fav_1.svg";

@override
void initState() {
 super.initState();
 getData();
}

getData() async{
 //var res = await http.get(Uri(host: url));
 var res = await http.get(Uri.https('www.*******.net', '/index.php',{'act':'sentmatches'}));
 data = jsonDecode(res.body);
 print(data);
 setState(() {});
 print(res.body);
}


@override
Widget build(BuildContext context){
 final Size size = MediaQuery.of(context).size;
 final ThemeData themeData = Theme.of(context);
 final double padding = 25;
 final sidePadding = EdgeInsets.symmetric(horizontal: padding);
 return
  data != null? Expanded(
        child: Padding(
          padding: sidePadding,
          child:  GridView.builder(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              //maxCrossAxisExtent: 200,
                crossAxisCount: 2,
                crossAxisSpacing: 20,
                mainAxisSpacing: 20,
              childAspectRatio: 0.75,
            ),
            itemCount: data.length,
            itemBuilder: (context, index) {
              return InkWell(
                onTap: () {
                  Auth.prefs?.setString('profid', data[index]['id']);

                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => Persondetail()),
                  );
                },
                child:  Container(
                  width: MediaQuery.of(context).size.width,
                  height: MediaQuery.of(context).size.height,
                  child: Stack(
                    children: [
                      Positioned(
                        top: 5,
                        right: 5,
                        child: InkWell(
                          onTap: () async{
                            usridf = data[index]['id'];
                            user = '${UsrID}';

                            final body = null;
                            final url = Uri.https('www.*******.net', '/index.php',{'act':'addfav','usridf': usridf, 'user': user});
                            final response = await http.post(
                                url,
                                headers: {'Content-Type': 'application/json'},
                                body: body
                            );
                            print(url);
                            int statusCode = response.statusCode;
                            //var responseBody = json.decode(response.body);
                            Map<String, dynamic> responseBody = jsonDecode(response.body);
                            setState(() {});

                            var list = responseBody['error'];
                            var stringList = list.join("\n");
                            print(stringList); //Prints "in new line"

                            var statusRes = responseBody['status'];
                            //var UserPhone = responseBody['phone'];
                            //var UserID = responseBody['usrid'];
                            if(statusRes == 'add success'){
                              print('success: '+statusRes);
                            } else if(statusRes == 'remove success') {
                              print('success: '+statusRes);
                            } else {
                              print('error: '+statusRes);
                            }


                            setState(() {
                              favicon = "assets/images/Fav_2.svg";
                            });
                          },
                          child: SvgPicture.asset(
                            width: 30,
                            favicon,
                            height: 30,
                          ),
                        ),
                      ),
                      Positioned(
                        bottom: 5,
                        left: 10,
                        right: 5,
                        child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children:[
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  //Row(
                                  //mainAxisAlignment: MainAxisAlignment.start,
                                  //children: <Widget>[
                                  SizedBox(width: 5.0),
                                  Text(
                                    data[index]['fulname'],
                                    style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 15
                                    ),
                                  ),
                                  addVerticalSpace(0),
                                  Text(
                                    'Dieppe, Canada.',
                                    style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 10
                                    ),
                                  )
                                  //],
                                  //),
                                ],
                              ),
                              Column(
                                //textDirection: TextDirection.rtl,
                                children: [
                                  CircleAvatar(
                                    radius: 18,
                                    backgroundColor: Color(0xff8f9df2),
                                    child: IconButton(
                                      icon: SvgPicture.asset(
                                        'assets/images/f_chat.svg',
                                        width: 18,
                                        height: 18,
                                      ),
                                      onPressed: () {},
                                    ),
                                  ),

                                ],
                              ),
                            ]
                        ),
                      ),
                    ],
                  ),

                  decoration: BoxDecoration(
                    color: Colors.black,
                    borderRadius: BorderRadius.circular(10),
                    image: DecorationImage(
                      fit: BoxFit.cover,
                      image: NetworkImage("https://www.*******.net/files/profile/${data[index]['profimage']}"),
                      colorFilter: ColorFilter.mode(Colors.black.withOpacity(0.3), BlendMode.darken),
                    ),
                  ),
                ),
              );
            },
          )
        )
    ): const Center(
    child: CircularProgressIndicator(),
  );
 }
 }

Please help me with how I do this and changed the SVG image/icon of that box that I click.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

若言繁花未落 2025-02-20 13:00:41

那是因为您正在为类变量设置图标,因此您面临此问题。

声明这样的favicon列表的变量。

String favicon = "assets/images/Fav_1.svg";
List<String> favIcons = [];

在您的getData方法中,这样修改以生成等于数据长度的n数字的粉丝。

getData() async{
    //var res = await http.get(Uri(host: url));
    var res = await http.get(Uri.https('www.*******.net', '/index.php',{'act':'sentmatches'}));
    data = jsonDecode(res.body);
    for (var element in data) {favIcons.add(favicon);}
    setState(() {});
  }

或者,您甚至可以将图标属性应用到数据中,并以后使用它,而无需创建单独的变量,您应该根据数据处理图标。我用简单的推动创建了一个列表。

在Tap方法上

onTap: () {
   favIcons[index] = "assets/images/Fav_2.svg";
   setState(() {});
}

,使用Favicon:

child: SvgPicture.asset(
    width: 30,
    favIcons[index],
    height: 30,
)

除此之外,请尝试使用SetState()一次进行操作。您称之为两次。

That's because you are setting the icon for the class variable and hence you are facing this issue.

Declare a variable for a list of favIcon like this.

String favicon = "assets/images/Fav_1.svg";
List<String> favIcons = [];

In your getData method modify like this to generate n numbers of favicons equal to the length of data.

getData() async{
    //var res = await http.get(Uri(host: url));
    var res = await http.get(Uri.https('www.*******.net', '/index.php',{'act':'sentmatches'}));
    data = jsonDecode(res.body);
    for (var element in data) {favIcons.add(favicon);}
    setState(() {});
  }

Or you can even app Icon property to the data and use it later without creating a separate variable and you should handle the icons based on the data. I created a list with a plain simple push.

And on tap method

onTap: () {
   favIcons[index] = "assets/images/Fav_2.svg";
   setState(() {});
}

And while using favIcon:

child: SvgPicture.asset(
    width: 30,
    favIcons[index],
    height: 30,
)

Apart from this, try to use setState() only once for an action. You are calling it twice.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文