[Flutter] 사용자 동작(제스터)를 감지하는 GestureDetector위젯

2020. 12. 12. 15:52Flutter

flutter에서 제스처를 감지하기 위해 onPressed  onTab을 직접 위젯에 넣는 대신에 GestureDetector 위젯을 이용해서 훨씬 더 많은 범위의 위젯을 감지할 수 있습니다. 

 ex) 길게 터치 (GestureTapCallback) , 끌기 (GestureDragStartCallback / GestureDragEndCallback) ,  강제누르기 (GestureForcePressPeakCallback) 등등 문서를 참조. 수많은 액션 클래스들이 정의되어 있습니다! 여기

 

GestureDetector class - widgets library - Dart API

A widget that detects gestures. Attempts to recognize gestures that correspond to its non-null callbacks. If this widget has a child, it defers to that child for its sizing behavior. If it does not have a child, it grows to fit the parent instead. By defau

api.flutter.dev

이 위젯은 모든 제스터를 감지합니다. 자식 위젯에 어떤 스타일이나 모양, 애니메이션을 강제로 적용하지 않습니다.

유저들과 상호작용 할 수 있는 가장 순수한 방법이라고 할 수 있습니다!

 

           // Expanded 클래스로 감싼 하나의 영역. ReusableCard라는 반복되는 카드를 감싸
           // gesture로 유저가 tap할 경우 해당 로직을 타도록 한다.
           Expanded(
                child: GestureDetector(
                  onTap: () {
                    print("dd");
                  },
                  child: ReusableCard(
                    receivedColor: activeCardColor,
                    cardChild:
                        IconContent(icon: FontAwesomeIcons.mars, label: 'Male'),
                  ),
               ),
            ),

onTap 

 가장 기본적인? 제스처 감지기 속성 중 하나입니다. 사용자가 탭을 했을 때 발생하는 콜백입니다. 여기에 특정 state의 값을 변경 시켜도 되고, 토스트 창을 띄워도 되고 기본적이지만 사용자 <-> 앱 간의 인터랙션이 생기게 되는 것입니다😊

 

setState로 탭할 경우 색상 변경하기

  Color maleCardColor = inactiveCardColor;
  Color femaleCardColor = inactiveCardColor;

  // 1 = male / 2 = female
  void updateColor(int gender) {
    if (gender == 1) {
      if (maleCardColor == inactiveCardColor) {
        maleCardColor = activeCardColor;
        femaleCardColor = inactiveCardColor;
      } else {
        maleCardColor = inactiveCardColor;
      }
    }
    if (gender == 2) {
      if (femaleCardColor == inactiveCardColor) {
        femaleCardColor = activeCardColor;
        maleCardColor = inactiveCardColor;
      } else {
        femaleCardColor = inactiveCardColor;
      }
    }
  }
              Expanded(
                child: GestureDetector(
                  onTap: () {
                    setState(() {
                      updateColor(1);
                    });
                  },
                  child: ReusableCard(
                    receivedColor: maleCardColor,
                    cardChild:
                        IconContent(icon: FontAwesomeIcons.mars, label: 'Male'),
                  ),
                ),
              ),