text
stringlengths
1
372
how do i add an onClick listener to a widget in flutter?
in android, you can attach onClick to views such as button by calling
the method ‘setonclicklistener’.
in flutter there are two ways of adding touch listeners:
<code_start>
@override
widget build(BuildContext context) {
return ElevatedButton(
onPressed: () {
developer.log('click');
},
child: const Text('Button'),
);
}
<code_end>
<code_start>
class SampleTapApp extends StatelessWidget {
const SampleTapApp({super.key});
@override
widget build(BuildContext context) {
return scaffold(
body: center(
child: GestureDetector(
onTap: () {
developer.log('tap');
},
child: const FlutterLogo(
size: 200,
),
),
),
);
}
}
<code_end>
<topic_end>
<topic_start>
how do i handle other gestures on widgets?
using the GestureDetector, you can listen to a wide range of gestures such as:
tap
double tap
long press
vertical drag
horizontal drag
the following example shows a GestureDetector
that rotates the flutter logo on a double tap:
<code_start>
class SampleApp extends StatefulWidget {
const SampleApp({super.key});
@override
State<SampleApp> createState() => _SampleAppState();
}
class _SampleAppState extends State<SampleApp>
with SingleTickerProviderStateMixin {
late AnimationController controller;
late CurvedAnimation curve;
@override
void initState() {
super.initState();
controller = AnimationController(
vsync: this,
duration: const duration(milliseconds: 2000),
);
curve = CurvedAnimation(
parent: controller,
curve: Curves.easeIn,
);
}
@override
widget build(BuildContext context) {
return scaffold(
body: center(
child: GestureDetector(
onDoubleTap: () {
if (controller.iscompleted) {
controller.reverse();
} else {
controller.forward();
}
},
child: RotationTransition(
turns: curve,
child: const FlutterLogo(
size: 200,
),
),
),
),
);
}
}
<code_end>
<topic_end>
<topic_start>
listviews & adapters
<topic_end>
<topic_start>
what is the alternative to a ListView in flutter?
the equivalent to a ListView in flutter is … a ListView!
in an android ListView, you create an adapter and pass it into the