Press "Enter" to skip to content

Flutter onPressed, onTap – The Basics for Adding Click Event for a Widget

In this lesson, we can learn the basics for adding click (onPressed / onTap) event to a Widget.

Adding an interactivity to a widget is simple. By adding an interactivity or event, there should be a change on the application or database. So the changing thing (may be a text or style) should be written as a public variable.

For example:

If we want to change the value of text, then its value should be a variable.

Here variable name declared as public (inside the extended widget)

String name = "no name";

We can call this variable for the value of a text.

Row(
  mainAxisAlignment: MainAxisAlignment.center,
  children: <Widget>[ 
      Text(name), 
  ],
),

 Now the output should be “no name”.

Events with TextField and Buttons are described here

Interactivity Based Widgets

All widgets do not support interactivity, there are special types for widget for adding events like onPressed.

Now let’s create a simple icon to add an interactivity (on Pressed). Instead of adding normal icon, you need to use IconButton widget for interactivity.

IconButton(
    icon: Icon(Icons.star),
    onPressed: () {
     // Interactivity or events codes here 
           }, 
 ), 

Where icon: Icon(Icons.add)  is an icon of star.

onPressed is the event, that works when we press on the star icon. You can write code inside the braze bracket.

If we want to change the state of a widget or to make some changes on style, then use the function setState() inside the onPressed section.

setState(() {
  //Changes here
});

If we want to change text on ‘name’, then we can do it using setState function.

IconButton(
    icon: Icon(Icons.star),
    onPressed: () {
      setState(() {
        name = "YourOwnCodes.com"; 
      });
      },
),

Here the value of the public value ‘name’ is changed into ‘YourOwnCodes.com’.

Flutter onPressed click event on icon

Interactivity for any type of Widgets

In above example we found, there is a special type of button (IconButton) for adding events (onPressed). Normally we cannot add events like onPressed, onTap on normal widgets. But there are some options to add interaction to any type of widgets.

GestureDetector

As the name indicates, the GestureDetector detects interaction to any widgets like Action listener in Java. If we want add any type of event, then include that widget as the child of GestureDetector.

Gesture Detector supports onTap event; which is similar to onPressed, that is you can manage tap events by this feature.

GestureDetector(
   child: new Text("Gesture"),
    onTap: () {
      setState(() {
        name = "Text by GestureDetector";
      });
    },
 ),

Here, a Text(Gesture) included as a child of the GestureDetector widget. Inside the onTap event, value of name changed into “Text by GestureDetector”.

GestureDetector for adding interactivity ontap event

InkWell

InkWell is similar to GestureDetector, you can add any widgets as the child of the InkWell widget.

InkWell(
    child: Container(
      child: Text("InkWell"),
    ),
    onTap:() {
      setState(() {
        name = "Text by InkWell";
      });
    },
  )

Here a container included as the child of the InkWell widget. Inside the onTap event, value of name changed into “Text by InkWell”.

flutter inkwell ontap event

Calling External Function

You can make event activity codes as an external function, so you can call them as you need in your program.

InkWell(
    child: Container(
      child: Text("InkWell"),
    ),
    onTap: changeName,
  )

Where changeName is the function name. So you need to explain the body for the function outside the inkwell widget but inside the build class .

void changeName() {
  setState(() {
       name = "Your own codes";
  });
}

All three components together:

import 'package:flutter/material.dart';
void main()
{
  runApp(
      MaterialApp(
        home: MyApp(),
      )
  );
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String name = "no name";
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        title: new Text("My App Title"),
      ),
      backgroundColor: Colors.white70,
      body:  Container(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                  Text(name),
              ],
            ),

            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: <Widget>[
                IconButton(
                    icon: Icon(Icons.star),
                    onPressed: () {
                      setState(() {
                        name = "YourOwnCodes.com";
                      });
                      },
                ),

               GestureDetector(
                child: new Text("Gesture"),
                 onTap: () {
                   setState(() {
                     name = "Text by GestureDetector";
                   });
                 },
              ),

              InkWell(
                  child: Container(
                    child: Text("InkWell"),
                  ),
                  onTap: changeName,
                )
              ],
            ),

          ],
        ),
      ),
    );
  }

  void changeName() {
    setState(() {
         name = "Your own codes";
    });
  }
}

Output:

Events with Button and TextField

All these three methods may not be feasible with button event with textfield content or value. so you need follow this method: TextField and Button Events using Controller

Be First to Comment

Leave a Reply