How can i change a Listile background color, leading icon color, trailing icon color by clicking onTap event?

55 Views Asked by At

actually i have a listile. i want to change its background color, leading icon color and prefix icon color when i am tapping on it.

         ListTile(
                leading: AppIcon.PERSON,
                trailing: Icon(Icons.arrow_right_alt_sharp),
                // hoverColor: AppColors.PRIMARY_COLOR_20,
                onTap: () {
                  print('tappers');
                },
                // selected: true,
                splashColor: AppColors.PRIMARY_COLOR_20,
                selectedTileColor: AppColors.PRIMARY_COLOR_20,
                selectedColor: AppColors.PRIMARY_COLOR_20,

                title: Text(
                  'Edit Account',
                  style: TextStyle(fontFamily: 'Inter'),
                ),
              ),
2

There are 2 best solutions below

0
On BEST ANSWER

Create a variable that will hold those color values.

  Color backgroundColor = Colors.white;
  Color leadingIconColor = Colors.red;
  Color trailingIconColor = Colors.red;

Assign those values to the parameters that needs the color. The setState will change the value of those colors inside the onTap parameter.

             ListTile(
              leading: Icon(Icons.account_circle, color: leadingIconColor,),
              trailing: Icon(Icons.arrow_right_alt_sharp, color: trailingIconColor),
              // hoverColor: AppColors.PRIMARY_COLOR_20,
              onTap: () {
                // Set the new values of the color variables.
                setState(() {
                  backgroundColor = Colors.grey;
                  leadingIconColor = Colors.white;
                  trailingIconColor = Colors.white;
                });
              },
              // selected: true,
              tileColor: backgroundColor,
              title: const Text(
                'Edit Account',
                style: TextStyle(fontFamily: 'Inter'),
              ),
            ),
0
On

@Shafi Munshi Kindly review the code below. It's a condensed solution that I believe will be beneficial.

ListTile(
      onTap: () {
        setState(() {
          isTapped = !isTapped;
        });
      },
      tileColor: isTapped ? Colors.blue : null, // Change background color
      leading: Icon(
        Icons.account_circle,
        color: isTapped ? Colors.red : null, // Change leading icon color
      ),
      title: Text('List Item'),
      trailing: Icon(
        Icons.favorite,
        color: isTapped ? Colors.green : null, // Change prefix icon color
      ),
    );