Handling Events and User Input in Flutter

This blog article will explore the exciting topic of handling user input and events in Flutter.

You’ll discover that user interaction is critical to developing exciting and dynamic Flutter mobile applications as you progress in your app development journey.

Let’s get down to the very details of how Flutter handles user input and events so that we can develop responsive, user-friendly apps.

Understanding User Input and Events

In Flutter, user input is any action a user performs responding to interactions like tapping buttons, typing text, or scrolling.

On the other side, events are the responses triggered by user input.

To deliver a seamless user experience, you must record these events as a Flutter developer and manage them accordingly.

Handling Button Taps

The user interface of any application must include buttons. Let’s look at how the ‘onPressed’ property may be used to manage button taps:

import 'package:flutter/material.dart';


class ButtonTapDemo extends StatelessWidget {
  const ButtonTapDemo({super.key});


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            // This function will be called when the button is tapped
            print('Hey There! How are you?');
          },
          child: const Text('Tap Me'),
        ),
      ),
    );
  }
}

In the above example, when the user taps the button, it will print ‘Hey There! How are you?’ to the console. Other than the print() function, we can perform many more actions when the button is tapped like, navigate to another screen, update the content, etc.

Handling Text Input

The TextField widget can be used to manage user-provided text input. Here is an example of how to retrieve user input from a text field:

import 'package:flutter/material.dart';
class TextFieldEventDemo extends StatefulWidget {
  const TextFieldEventDemo({super.key});


  @override
  _TextFieldEventDemoState createState() => _TextFieldEventDemoState();
}


class _TextFieldEventDemoState extends State<TextFieldEventDemo> {
  String input = '';
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TextField(
              onChanged: (value) {
                // This function is called whenever the user types in the text field
                setState(() {
                  input = value;
                });
              },
              decoration: const InputDecoration(
                labelText: 'Write something',
                border: OutlineInputBorder(),
              ),
            ),
            Text(input)
          ],
        ),
      ),
    );
  }
}

In this example, we have used a StatefulWidget which shows that the TextField widget takes the input from the user and updates the text below it. Whenever the user will type in the textfield, the onChange method of the TextField will be triggered and the state of the text below it will be changed.

Gestures Handling

Flutter has a variety of widgets to handle various gestures, including tapping, swiping, and dragging.

Let’s look at an illustration of how the GestureDetector widget handles a tap gesture:

import 'package:flutter/material.dart';


class GestureDetectorDemo extends StatelessWidget {
  const GestureDetectorDemo({super.key});


  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        // This function is called when the user taps anywhere on the widget
        print('Screen tapped!');
      },
      child: const Scaffold(
        body: Center(
          child: Text(
            'Tap anywhere on the screen',
          ),
        ),
      ),
    );
  }
}

In this example, we have wrapped the whole screen in the GestureDetector. So, when the user taps anywhere on the screen, the ‘onTap’ function is triggered and ‘Screen tapped!’ will be printed in the console.

Flutter Developers from Flutter Agency

Handle Slider Changes

Sliders help choose a value from a range. To track and react to changes in slider value, utilize Flutter’s Slider widget.

import 'package:flutter/material.dart';


class SliderDemo extends StatefulWidget {
  const SliderDemo({super.key});


  @override
  _SliderDemoState createState() => _SliderDemoState();
}


class _SliderDemoState extends State<SliderDemo> {
  int _value = 35;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(15.0),
          child: Center(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              mainAxisSize: MainAxisSize.max,
              children: [
                SizedBox(
                  width: 70,
                  child: Icon(
                    Icons.volume_up,
                    size: _value.toDouble(),
                  ),
                ),
                Expanded(
                  child: Slider(
                    value: _value.toDouble(),
                    min: 10.0,
                    max: 60.0,
                    divisions: 10,
                    activeColor: Colors.deepPurple,
                    inactiveColor: Colors.orange,
                    label: _value.toString(),
                    onChanged: (double newValue) {
                      setState(() {
                        _value = newValue.round();
                      });
                    },
                    semanticFormatterCallback: (double newValue) {
                      return '${newValue.round()} dollars';
                    },
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

In this example, we have a sound icon and a slider next to it, based on the slider’s value the size of the sound icon will be changed. When the user drags the slider’s head, the onChanged() function will be triggered and the size of the sound icon will be changed.

Handling Checkbox Changes

Binary choices are frequently selected using checkboxes. You can monitor changes in the checkbox’s state and respond to them using Flutter’s Checkbox widget.

import 'package:flutter/material.dart';


class CheckBoxDemo extends StatefulWidget {
  const CheckBoxDemo({super.key});


  @override
  _CheckBoxDemoState createState() => _CheckBoxDemoState();
}


class _CheckBoxDemoState extends State<CheckBoxDemo> {
  bool? valuefirst = false;
  bool? valuesecond = false;


  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SizedBox(
            child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            const Text(
              'Checkbox without Header and Subtitle:',
              style: TextStyle(fontSize: 15.0),
            ),
            Row(
              children: <Widget>[
                Checkbox(
                  // checkColor: Colors.greenAccent,
                  // activeColor: Colors.red,
                  value: valuefirst,
                  onChanged: (bool? value) {
                    setState(() {
                      valuefirst = value;
                    });
                  },
                ),
                Text(valuefirst.toString())
              ],
            ),
            Row(
              children: [
                Checkbox(
                  value: valuesecond,
                  onChanged: (bool? value) {
                    setState(() {
                      valuesecond = value;
                    });
                  },
                ),
                Text(valuesecond.toString())
              ],
            )
          ],
        )),
      ),
    );
  }
}

In this example, there are two checkBoxes whose byDefault value is false and when tapped, the onChanged() function is triggered and the value of that particular checkbox is set to true.

Conclusion

Handling user input and events is essential to creating responsive Flutter applications. Using several Flutter widgets and callbacks, we explored how to handle button taps, collect text input, detect gestures, respond to checkbox changes, and handle slider interactions.

Congratulations on mastering the art of using Flutter to handle user input and events!

Hence, these abilities enable you to develop responsive and responsive and fascinating apps. Visit www.flutteragency.com to stay updated on the latest Flutter trends, best practices, and development tips.

Frequently Asked Questions (FAQs)

1. Which widget does Flutter use for user input?

Flutter uses various widgets to handle user inputs such as, gesture detector, inkwell, textfield, checkbox, button, etc. The most popular widget for user input is textfield.

2. How does Flutter handle user input?

Flutter provides us with a very rich set of widgets and event handling mechanisms. Using these widgets and event handlers, developers can easily capture and respond to user input which makes the application user friendly and responsive.

3. How to Handle User Input and Events in Flutter?

To manage user input and events in Flutter:

1. Select the appropriate widget based on the desired user input, like TextField, GestureDetector, InkWell, Checkbox, Radio, Switch, Slider, DropdownButton, etc.
2. Attach event handlers to widgets that respond to user interactions. These handlers, or callback functions, execute when the corresponding events occur.
3. Use the TextField widget to capture textual input. You can provide a controller to track and manipulate the input and define callbacks for text changes.

By following these steps, you can efficiently handle user input and events in Flutter, creating a seamless and interactive user experience.

Book Your Flutter Developer Now

Abhishek Dhanani

Written by Abhishek Dhanani

Abhishek Dhanani, a skilled software developer with 3+ years of experience, masters Dart, JavaScript, TypeScript, and frameworks like Flutter and NodeJS. Proficient in MySQL, Firebase, and cloud platforms AWS and GCP, he delivers innovative digital solutions.

Leave a comment

Your email address will not be published. Required fields are marked *


Discuss Your Project

Connect with Flutter Agency's proficient skilled team for your app development projects across different technologies. We'd love to hear from you! Fill out the form below to discuss your project.

Have Project For Us

Get in Touch

"*" indicates required fields

ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields