[Flutter] GestureDetector란?

김근재·2024년 7월 12일

[Flutter] 시리즈 

목록 보기
10/10
post-thumbnail

Flutter의 GestureDetector란 무엇인가?

Flutter의 강력한 기능 중 하나는 다양한 제스처를 감지하고 처리할 수 있는 GestureDetector 위젯입니다. 이번 블로그에서는 GestureDetector에 대해 자세히 알아보고, 어떻게 사용되는지 예제를 통해 설명하겠습니다.

GestureDetector란?
GestureDetector는 Flutter에서 사용자의 터치 제스처를 감지하는 데 사용되는 위젯입니다. 버튼 클릭, 드래그, 스와이프 등 다양한 제스처를 감지하고 이에 따라 특정 동작을 수행할 수 있습니다. GestureDetector는 단일 제스처뿐만 아니라 여러 가지 복합적인 제스처도 처리할 수 있어 매우 유용합니다.

주요 기능

GestureDetector는 다양한 제스처를 감지할 수 있으며, 주요 기능은 다음과 같습니다:

onTap: 사용자가 화면을 한 번 탭했을 때 호출됩니다.
onDoubleTap: 사용자가 화면을 두 번 빠르게 탭했을 때 호출됩니다.
onLongPress: 사용자가 화면을 길게 눌렀을 때 호출됩니다.
onPanUpdate: 사용자가 화면을 끌 때 호출됩니다.
onScaleUpdate: 사용자가 화면을 두 손가락으로 확대/축소할 때 호출됩니다.
GestureDetector 사용 예제

아래 예제 코드는 GestureDetector를 사용하여 화면을 탭했을 때 배경색이 변경되는 간단한 애플리케이션입니다.

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: GestureDetectorExample(),
    );
  }
}

class GestureDetectorExample extends StatefulWidget {
  @override
  _GestureDetectorExampleState createState() => _GestureDetectorExampleState();
}

class _GestureDetectorExampleState extends State<GestureDetectorExample> {
  Color _backgroundColor = Colors.white;

  void _changeBackgroundColor() {
    setState(() {
      _backgroundColor = _backgroundColor == Colors.white ? Colors.blue : Colors.white;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('GestureDetector Example'),
      ),
      body: GestureDetector(
        onTap: _changeBackgroundColor,
        child: Container(
          color: _backgroundColor,
          child: Center(
            child: Text(
              'Tap anywhere to change background color',
              style: TextStyle(fontSize: 20),
            ),
          ),
        ),
      ),
    );
  }
}

제스처 조합

GestureDetector는 여러 제스처를 동시에 감지하고 처리할 수 있습니다. 예를 들어, 사용자가 화면을 길게 누르고 있는 동안 드래그 동작을 감지할 수 있습니다. 이를 위해서는 각 제스처에 대한 콜백 함수를 정의하면 됩니다.

class GestureDetectorExample extends StatefulWidget {
  @override
  _GestureDetectorExampleState createState() => _GestureDetectorExampleState();
}

class _GestureDetectorExampleState extends State<GestureDetectorExample> {
  String _gestureText = 'No Gesture detected';

  void _updateText(String text) {
    setState(() {
      _gestureText = text;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('GestureDetector Example'),
      ),
      body: GestureDetector(
        onTap: () => _updateText('Tap detected'),
        onDoubleTap: () => _updateText('Double Tap detected'),
        onLongPress: () => _updateText('Long Press detected'),
        onPanUpdate: (details) => _updateText('Pan detected: ${details.delta}'),
        child: Center(
          child: Text(
            _gestureText,
            style: TextStyle(fontSize: 24),
          ),
        ),
      ),
    );
  }
}

결론

GestureDetector는 Flutter 애플리케이션에서 사용자 입력을 감지하고 처리하는 데 매우 유용한 도구입니다. 다양한 제스처를 쉽게 처리할 수 있어 사용자 인터페이스를 보다 직관적이고 반응적으로 만들 수 있습니다.

profile
새로운 도전에 끊임없이 도전하는 개발자

0개의 댓글