0

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.

RAF Algowid
  • 87
  • 2
  • 6
  • can you add screenshots? is favIcon is issue? if in that case which one to change you have two svg being used placed in stack? – Prabhakaran Jul 05 '22 at 08:16
  • yes in the first. `favicon' . variable there is default icon which comes onload screen but I want to change icon when clicking on `onTap of Inkwell()` and in setstate i add second icon – RAF Algowid Jul 05 '22 at 08:33

1 Answers1

0

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.

Prabhakaran
  • 1,524
  • 2
  • 13
  • 21