본문 바로가기
Flutter

[Flutter] change widget color on tap ; 눌린 위젯 색상변경하기

by hymndaniel 2022. 5. 11.

Motivation

사용자가 선택한 항목이 무엇인지 알려주기위해, 선택된 container 의 border color를 변경시켜주기

 

선택된 인덱스 초기설정. index는 0부터 시작함. 초기에는 아무것도 선택되지 않았기 때문에 -1로 시작. 

_selectedIndex = -1;

 

Listview로 여러개의 container를 그려주는 상황.

setState로 사용자가 선택한 index를 선택된 인덱스와 같은 값으로 설정

InkWell(
  onTap: () {
    setState(() {
      _selectedIndex = index;
    });
  },

 

인덱스가 선택된 값과 같으면 색상을 변경

Container(
  margin: const EdgeInsets.only(bottom: 8),
  decoration: BoxDecoration(
    color: const Color(0xfff9f9f9),
    borderRadius: BorderRadius.circular(10),
    border: Border.all(
      color: index == _selectedIndex ? Colors.black54 : Colors.transparent,
    ),
  ),
 

 

 

Reference

https://stackoverflow.com/questions/64236695/change-color-on-tap-in-a-flutter-application

 

Change color on tap in a Flutter application

I am trying to change the color of card on tap which was created by ListView.Builder. I tried with Inkwell and wrapping the listview inside container. Now problem is if I click or tap on any list i...

stackoverflow.com

Step 1: Define index with default value of -1

int _selectedIndex = -1;

Step 2: Update index on click of list item

InkWell(
    onTap: () {
      setState(() {
        if(_selectedIndex == index){
          _selectedIndex= -1;
         }else{
         _selectedIndex= index;
        }
      });
    },

Step 3: Update your item color logic

 decoration: BoxDecoration(color: index== _selectedIndex  ? 
                                  Colors.deepOrangeAccent : 
                                  Colors.purpleAccent,),

 

https://stackoverflow.com/questions/52111963/how-to-color-selected-listitem-ontap

 

How to color selected ListItem onTap

I want to color select value from a ListView like this : The problem is I print all when I try it , code : class _ProcedureList extends State<ProcedureList> { bool isSelected = true;

stackoverflow.com

 

 
728x90