Search code examples
flutterflutter-list-tile

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


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'),
                ),
              ),

Solution

  • 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'),
                  ),
                ),