Flutter

Flutter – GestureDetector Code Example & Concepts

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. 

  • Capture user’s gesture using a widget called as GestureDetector. The following happens as part of GestureDetector widget:
    • Capture events such as onTap, onDoubleTap etc and change the state
  • After the user gesture is captured and the state is changed, the widget is built and replaced with existing widget. The existing widget is flagged as dirty.

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.

Ajitesh Kumar

I have been recently working in the area of Data analytics including Data Science and Machine Learning / Deep Learning. I am also passionate about different technologies including programming languages such as Java/JEE, Javascript, Python, R, Julia, etc, and technologies such as Blockchain, mobile computing, cloud-native technologies, application security, cloud computing platforms, big data, etc. I would love to connect with you on Linkedin. Check out my latest book titled as First Principles Thinking: Building winning products using first principles thinking.

Share
Published by
Ajitesh Kumar
Tags: flutter

Recent Posts

Chunking Strategies for RAG with Examples

If you've built a "Naive" RAG pipeline, you've probably hit a wall. You've indexed your…

5 days ago

RAG Pipeline: 6 Steps for Creating Naive RAG App

If you're starting with large language models, you must have heard of RAG (Retrieval-Augmented Generation).…

6 days ago

Python: List Comprehension Explained with Examples

If you've spent any time with Python, you've likely heard the term "Pythonic." It refers…

1 week ago

Large Language Models (LLMs): Four Critical Modeling Stages

Large language models (LLMs) have fundamentally transformed our digital landscape, powering everything from chatbots and…

3 months ago

Agentic Workflow Design Patterns Explained with Examples

As Large Language Models (LLMs) evolve into autonomous agents, understanding agentic workflow design patterns has…

3 months ago

What is Data Strategy?

In today's data-driven business landscape, organizations are constantly seeking ways to harness the power of…

3 months ago