GestureDetector for capturing user gesture
In this post, we will learn about how to use GestureDetector with Stateful widgets in order to record changes to state. The following are key aspects in relation to changing state of the widget based on the users’ gesture.
Here is the code representing the usage of GestureDetector for capturing user gesture, changing the state of the widget and rebuilding the widget tree again. Note that the elements tree remain intact. In the code below, the VoteCounter is a stateful widget. As it gets created, the related element is created and put it on elements tree. The element then ask the VoteCounter widget to create the state. The state is created and a reference is passed on to element in the element tree. As a result of creation of state, the build method is called which results in creation of widgets such as GestureDetector and Text widget.
class VoteCounter extends StatefulWidget {
final String label = 'Vote';
@override
_VoteCounterState createState() => _VoteCounterState();
}
class _VoteCounterState extends State<VoteCounter> {
int count = 0;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
setState(() {
count++;
});
},
onDoubleTap: () {
setState(() {
count += 5;
});
},
child: Text('${widget.label}: $count'),
);
}
}
The above VoteCounter widget can be called from other widgets to display on the screen. Here is the sample code calling the VoteCounter stateful widget.
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Hello World App',
home: Scaffold(
appBar: AppBar(
title: Text('Welcome to Hello World'),
),
body: Center(
child: VoteCounter(),
),
)
);
}
}
Here is how this would look on the screen. Tapping once results in incrementing the vote by 1. Doing a double tapping results in vote increment by 5 as per the code given above.
Last updated: 25th Jan, 2025 Have you ever wondered how to seamlessly integrate the vast…
Hey there! As I venture into building agentic MEAN apps with LangChain.js, I wanted to…
Software-as-a-Service (SaaS) providers have long relied on traditional chatbot solutions like AWS Lex and Google…
Retrieval-Augmented Generation (RAG) is an innovative generative AI method that combines retrieval-based search with large…
The combination of Retrieval-Augmented Generation (RAG) and powerful language models enables the development of sophisticated…
Have you ever wondered how to use OpenAI APIs to create custom chatbots? With advancements…