좋아요! Flutter에서 GestureDetector는 사용자의 터치 제스처(탭, 드래그, 핀치 등)를 감지하고 이에 반응할 수 있게 도와주는 위젯이에요. 이 위젯은 인터페이스에 다양한 상호작용을 추가할 때 유용해요.
GestureDetector는 자식 위젯을 감싸고, 제스처를 감지했을 때 특정 콜백 함수를 실행하도록 설정할 수 있어요.
GestureDetector(
onTap: () {
print('화면을 탭했습니다!');
},
onDoubleTap: () {
print('더블 탭!');
},
onLongPress: () {
print('길게 누름!');
},
onPanUpdate: (details) {
print('드래그 중: ${details.delta}');
},
child: Container(
color: Colors.blue,
width: 200,
height: 200,
child: Center(
child: Text(
'GestureDetector',
style: TextStyle(color: Colors.white),
),
),
),
)
탭 관련
onTap: 단순 탭onDoubleTap: 두 번 빠르게 탭onLongPress: 길게 누름드래그 관련
onPanStart: 드래그 시작onPanUpdate: 드래그 중 위치 변화를 감지onPanEnd: 드래그가 끝났을 때스와이프 관련
onHorizontalDragStart, onHorizontalDragUpdate, onHorizontalDragEnd: 수평 드래그 감지onVerticalDragStart, onVerticalDragUpdate, onVerticalDragEnd: 수직 드래그 감지기타
onScaleStart, onScaleUpdate, onScaleEnd: 확대/축소 제스처 감지onTapDown, onTapUp, onTapCancel: 탭 세부 단계 감지사용자가 화면을 탭하거나 드래그할 때 배경색을 변경하는 예제를 만들어볼게요.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
Widget build(BuildContext context) {
return MaterialApp(
home: GestureExample(),
);
}
}
class GestureExample extends StatefulWidget {
_GestureExampleState createState() => _GestureExampleState();
}
class _GestureExampleState extends State<GestureExample> {
Color _backgroundColor = Colors.white;
void _changeColor() {
setState(() {
_backgroundColor = _backgroundColor == Colors.white
? Colors.green
: Colors.white;
});
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('GestureDetector Example'),
),
body: GestureDetector(
onTap: _changeColor,
child: Container(
color: _backgroundColor,
child: Center(
child: Text(
'Tap anywhere!',
style: TextStyle(fontSize: 24),
),
),
),
),
);
}
}
이 코드를 실행하면 화면을 탭할 때마다 배경색이 바뀌어요!