본문 바로가기
Flutter

[Flutter/플러터] getx를 사용하여 like 버튼(하트 버튼) 만들기

by 얘리밍 2022. 9. 23.
320x100
728x90

 

1. obs 변수를 만들어준다

var like = false.obs;

 

 

2. Obx 로 감싼 뒤, 위젯을 리턴해준다

Obx(() => CircleAvatar(
                  backgroundColor: Colors.white,
                  radius: 15,
                  child: Center(
                    child: IconButton(
                      ...
                    ),
                  ),
                ),
              ),

 

 

3. 삼항 연산자를 사용해 조건에 알맞은 아이콘을 보여주도록 한다.

product.like.value ? Icon(Icons.favorite_rounded) : Icon(Icons.favorite_border),

 

 

 

4. 눌렀을 때, 이벤트 처리

onPressed: () {
	product.like.toggle();
  },

 


 

Obx(() => CircleAvatar(
                  backgroundColor: Colors.white,
                  radius: 15,
                  child: Center(
                    child: IconButton(
                      alignment:Alignment.center,
                      icon: product.like.value ? Icon(Icons.favorite_rounded) : Icon(Icons.favorite_border),
                      onPressed: () {
                        product.like.toggle();
                      },
                      iconSize: 18,
                    ),
                  ),
                ),
              ),
728x90
반응형