Programming/Flutter
[Flutter] GestureDetector & InkWell 위젯
scii
2020. 10. 8. 23:26
글자나 그림 같이 이벤트 프로퍼티가 없는 위젯에 이벤트를 적용하고 싶을 때 사용하는 위젯이다.
GestureDetector와 InkWell 위젯은 터치 이벤트를 발생시킨다. onTab 프로퍼티를 가지고 있어서 child 프로퍼티에 어떠한 위젯이 와도 클릭 이벤트를 작성할 수 있다. 따라서 Text, Image 등의 위젯에도 간단히 클릭 이벤트를 추가할 수 있다.
GestureDetector(
onTab: () {
// 클릭 시 실행
},
child: [위젯],
),
InkWell(
onTab: () {
// 클릭 시 실행
},
child: [위젯],
),
InkWell 위젯으로 감싸고 클릭하면 물결 효과가 나타나지만 GestureDetector 위젯은 그렇지 않다.
GestureDetector & InkWell 위젯의 예제
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: '플러터 테스트'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new GestureDetector(
onTap: () {
print('GestureDetector 클릭!');
},
child: new Text('클릭 me!'),
),
SizedBox(
height: 40,
),
InkWell(
onTap: () {
print('Inkwell 클릭!');
},
child: new Text('클릭 me!'),
),
],
),
);
}
}
print() 함수로 출력한 결과는 에디터 콘솔에 나타난다.