카드 뒤집기 기능 구현

2023. 8. 13. 17:50개발공부/Flutter (ft.Dart)

우선 flip effect를 manage하기위한 StatefulWidget을 만들어주었다.

class Cards extends StatefulWidget {
  final String cardTitle;
  final List result;
  final String question;

  Cards({
    Key? key,
    required this.cardTitle,
    required this.result,
    required this.question,
  }) : super(key: key);

  @override
  _CardsState createState() => _CardsState();
}

그리고 handleCardClick이라는 함수를 만들어 isFlipped state를 toggle시켜주고 selectedCardIndex에 클릭한 카드의 인덱스 넘버를 넣어준다.

void handleCardClick(BuildContext context, int index) {
    setState(() {
      isFlipped = !isFlipped;
      selectedCardIndex = index;
    });
  }

그리고 아래는 scaffold widget의 children이다. onTap을 사용해 handleCardClick함수를 불러준다. 

children: List.generate(widget.result.length, (index) {
          return Padding(
            padding: EdgeInsets.all(3.0),
            child: GestureDetector(
              onTap: () => handleCardClick(context, index),
                child: isFlipped && selectedCardIndex == index
                    ? Container(
                  key: ValueKey<int>(index),
                  child: Card(
                    color: cardColors[index % cardColors.length],
                    elevation: 2,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Center(
                      child: Text(
                        widget.result[index],
                        textAlign: TextAlign.center, // Center-align the text
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 13,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),
                )
                    : Container(
                  key: ValueKey<int>(-index),
                  child: Card(
                    color: Colors.grey, // Back of the card color
                    elevation: 2,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Center(
                      child: Icon(
                        Icons.flip,
                        color: Colors.white,
                        size: 40.0,
                      ),
                    ),
                  ),
                ),
              ),
          );

카드 flip시 animation은 ui를 너무 촌스럽게 만드는거같아 일부러 넣지않았다. 하지만 현재의 문제는 인덱스넘버로 flip상태 구분을 해주기때문에 여러 장의 카드가 동시에 open이 안되는 점이다. 이 부분을 고려하여 다시 코드를 짜봐야겠다😅