Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What are Flutter Gestures?
3.
Pointers
4.
Gestures
5.
Gesture Detector
5.1.
Example:
5.1.1.
Output:
5.1.2.
Explanation: 
6.
Flutter Widgets
7.
Frequently Asked Questions
7.1.
What is a Spacer Widget?
7.2.
What are the Flutter Widgets?
7.3.
What do you understand by the Stateful and Stateless widgets?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

Flutter Gestures

Author Akash Nagpal
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Flutter is an open-source framework for developing high-quality, high-performance mobile apps for Android and iOS. It provides a simple, powerful, efficient, and straightforward SDK for developing mobile applications in Google's language, Dart. Dart is a general-purpose, object-oriented programming language with C-style syntax created by Google in 2011. Dart programming is used to construct frontend user interfaces for online and mobile apps. Here in this blog, we will be learning about Flutter Pointers and Gestures in detail with the help of various examples.

What are Flutter Gestures?

Flutter's gestures are an intriguing feature that allows us to interact with the mobile app (or any touch-based device). In general, gestures are any physical motion or movement a user performs to control a mobile device. Here are some examples of gestures:

  • When the smartphone screen is locked, you unlock it by swiping your finger over it.
  • Tapping a button on your smartphone screen or dragging an app icon between screens on a touch-based device

Flutter divides the gesture system into two different layers, which are given below:

  1. Pointers
  2. Gestures
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Pointers

The first layer is pointers, which represent basic data regarding user interaction. It provides events that explain the location and movement of points across the displays, such as touches, mice, and style. Flutter does not provide a means for cancelling or stopping the dispatch of pointer events. Flutter has a Listener widget that lets you listen to pointer events straight from the widgets layer. The pointer events are classified into four types:

  • PointerDownEvents
  • PointerMoveEvents
  • PointerUpEvents
  • PointerCancelEvents

Gestures

The second layer is the gestures representing semantic actions like tap, drag, and scale detected from many individual pointer events. It can also send out several events related to the gesture lifecycle, such as drag start, drag update, and drag end.

 

The following are some examples of commonly used gestures:

Tap: This involves briefly contacting the screen's surface with your fingertip and releasing it. The following occurrences occur as a result of this gesture:

  • onTapDown
  • onTapUp
  • onTap
  • onTapCancel

 

Double Tap: Similar to a Tap gesture, except you must tap twice in a brief period. The following occurrences occur as a result of this gesture:

  • onDoubleTap

 

Drag: It enables us to contact the screen's surface with our fingertip, move it from one spot to another, and then release them. Flutter classifies drag into two types:

  • Horizontal Drag: This motion allows the cursor to travel horizontally. It includes the following events:
    onHorizontalDragStart,
    onHorizontalDragUpdate,
    onHorizontalDragEnd
  • Vertical Drag: This action enables the cursor to travel vertically. It includes the following events:
    onVerticalDragStart,
    onVerticalDragStart,
    onVerticalDragStart

 

Long Press refers to prolonged contact with the screen's surface at a specific place. The following occurrences occur as a result of this gesture:

  • onLongPress

 

Pan: This involves touching the screen's surface with a fingertip that can travel in any direction without being released. The following occurrences occur as a result of this gesture:

  • onPanStart
  • onPanUpdate
  • onPanEnd

 

Pinch refers to zooming into or out of a screen by pinching (moving one's finger and thumb or bringing them together on a touchscreen).

Gesture Detector

Using the GestureDetector widget, Flutter provides great support for all forms of motion. The GestureWidget is a non-visual widget used to detect the user's gesture. The gesture detector's core concept is a stateless widget with constructor parameters for various touch events.

In some cases, there may be numerous gesture detectors in the same area on the screen, and the framework determines which gesture should be called. The GestureDetector widget determines which gestures to identify based on which of its callbacks is not null.

Example:

Let's see how we can use these gestures in our app with a simple onTap() event and how the GestureDetector handles it. In this section, we will construct a box widget, design it to our specifications, and then add the onTap() code. Create a new Flutter project and change the code below in the main.dart file.

Code:

import 'package:flutter/material.dart';  
  
void main() => runApp(MyApp());  
  
class MyApp extends StatelessWidget {  
  // This widget is the root of the application.  
  @override  
  Widget build(BuildContext context) {  
    return MaterialApp(  
      title: 'Flutter Demo Application', theme: ThemeData(  
      primarySwatch: Colors.green,),  
      home: MyHomePage(),  
    );  
  }  
}  
class MyHomePage extends StatefulWidget {  
  @override  
  MyHomePageState createState() => new MyHomePageState();  
}  
  
class MyHomePageState extends State<MyHomePage> {  
  @override  
  Widget build(BuildContext context) {  
    return new Scaffold(  
      appBar: new AppBar(  
        title: new Text('Gestures Example'),  
        centerTitle: true,  
      ),  
      body: new Center(child: GestureDetector(  
          onTap: () {  
            print('Box Clicked');  
          },  
          child: Container(  
            height: 60.0,  
            width: 120.0,  
            padding: EdgeInsets.all(10.0),  
            decoration: BoxDecoration(  
              color: Colors.blueGrey,  
              borderRadius: BorderRadius.circular(15.0),  
            ),  
            child: Center(child: Text('Click Me')),  
          )  
      )),  
    );  
  }  
}  

Output:

When you run this dart file in Android Studio, it will give the following output in the emulator.

 


Explanation: 

A button with rounded corners can be seen in the centre of the screen in the output image above. When you tap on it, it acts as a button, and the output is displayed in the console.

Flutter Widgets

Flutter further has widgets for performing particular and complex motions. These are the widgets:

  • Dismissible: Allows the widget to be dismissed by using a flick motion.
  • Draggable: This allows you to make the widget mobile by dragging it.
  • LongPressDraggable: If the parent widgets are draggable, the children's widget can be moved using the drag gesture.
  • DragTarget: Accepts any widget that can be dragged.
  • IgnorePointer: When activated, IgnorePointer conceals the widget and its descendants from the gesture detection process.
  • AbsorbPointer: To avoid action dispatch on overlapping widgets, AbsorbPointer stops the gesture detection process.
  • Scrollable: Makes the material within the widget scrollable.

Frequently Asked Questions

What is a Spacer Widget?

The Spacer class is used to generate a movable blank space. This empty area is utilised by the flex container to control the spacing between the widgets. In the function Object() { [native code] }, spacer uses flex to determine the spacing.

What are the Flutter Widgets?

A Flutter app is usually thought of as a widget tree. Every piece of code you write in Flutter will be contained within a widget. Widgets define how your app's view should appear in its current setup and state. When you changed the code, the widget regenerated its description by calculating the difference between the old and current widgets to decide the minimal adjustments for rendering in the app's UI.

What do you understand by the Stateful and Stateless widgets?

A Stateful widget contains state data. It is called dynamic because the inside data might change over the widget's lifespan. A Stateful widget is one that allows us to refresh the screen. This widget lacks a construct() function. It provides a method called createState() that returns a class that extends the Flutters State Class. Checkbox, Radio, Slider, InkWell, Form, and TextField are examples of Stateful widgets.

The Stateless widget has no state information. Throughout its existence, it stays motionless. Text, Row, Column, Container, and other Stateless widgets are examples. If the screen or widget includes static material, it should be a Stateless widget; however, if the content needs to be changed, it must be a Stateful widget.

Conclusion

In this article, we have extensively discussed Flutter Gestures and Pointers with the help of various examples. We have also brushed up on some of the concepts regarding Flutter widgets. We hope this blog has helped you enhance your knowledge regarding the Flutter concepts. 

If you would like to learn more, check out our articles on Flutter App Developmentcloud platform comparison, and 10 AWS best books. Practice makes a man perfect. To practice and improve yourself in the interview, you can check out Top 100 SQL problemsInterview experienceCoding interview questions, and the Ultimate guide path for interviews. Do upvote our blog to help other ninjas grow. Happy Coding!

Previous article
Flutter layouts
Next article
GetX Flutter
Live masterclass