Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

Flutter - Handling User Input

13. Handling User Input (Buttons, TextFields, etc.)

Handling user input is a fundamental aspect of building interactive Flutter apps. In this comprehensive tutorial, we'll cover how to work with various user input elements such as buttons, text fields, and more, and demonstrate how to respond to user actions.

1. Buttons

Buttons are a common way for users to interact with your app. Flutter provides several types of buttons, including 'ElevatedButton', 'TextButton', and 'OutlinedButton'.

Example: Using 'ElevatedButton'
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'User Input Tutorial',
      home: ButtonExample(),
    );
  }
}

class ButtonExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Button Example'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            // Handle button press here
            print('Button pressed!');
          },
          child: Text('Press Me'),
        ),
      ),
    );
  }
}
 

In this example, we use an 'ElevatedButton' widget, which is a Material Design button that elevates when pressed. When the button is pressed, the 'onPressed' callback is executed, and it prints a message to the console.

2. Text Fields

Text fields allow users to input text. Flutter provides the 'TextField' widget for this purpose.

Example: Using 'TextField'
class TextFieldExample extends StatefulWidget {
  @override
  _TextFieldExampleState createState() => _TextFieldExampleState();
}

class _TextFieldExampleState extends State {
  final TextEditingController _controller = TextEditingController();
  String _inputText = '';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Text Field Example'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(
              controller: _controller,
              onChanged: (text) {
                setState(() {
                  _inputText = text;
                });
              },
              decoration: InputDecoration(
                labelText: 'Enter Text',
              ),
            ),
            SizedBox(height: 16.0),
            Text('Input Text: $_inputText'),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}
 

In this example, we create a 'TextField' widget with a 'TextEditingController' to manage the text input. The 'onChanged' callback is called whenever the user types, and it  updates the '_inputText' variable, which is displayed below the text field.

3. Checkboxes and Radio Buttons

Checkboxes and radio buttons are used to capture binary and mutually exclusive choices, respectively.

Example: Using 'Checkbox' and 'Radio' Widgets
class CheckboxRadioExample extends StatefulWidget {
  @override
  _CheckboxRadioExampleState createState() => _CheckboxRadioExampleState();
}

class _CheckboxRadioExampleState extends State {
  bool _isChecked = false;
  int _selectedRadio = 0;

  void _handleRadioValueChange(int value) {
    setState(() {
      _selectedRadio = value;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Checkbox and Radio Example'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            Checkbox(
              value: _isChecked,
              onChanged: (value) {
                setState(() {
                  _isChecked = value!;
                });
              },
            ),
            SizedBox(height: 16.0),
            Row(
              children: [
                Radio(
                  value: 0,
                  groupValue: _selectedRadio,
                  onChanged: _handleRadioValueChange,
                ),
                Text('Option 1'),
              ],
            ),
            Row(
              children: [
                Radio(
                  value: 1,
                  groupValue: _selectedRadio,
                  onChanged: _handleRadioValueChange,
                ),
                Text('Option 2'),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
 

In this example, we use a 'Checkbox' to capture a binary choice and 'Radio' widgets to capture a mutually exclusive choice. The 'onChanged' callback is used to update the selected value when the user interacts with these widgets.

4. Handling Form Submissions

Forms are used to collect and submit multiple user inputs. Flutter provides the Form widget to manage form state and validation.

Example: Using 'Form' and Form Fields
class FormExample extends StatefulWidget {
  @override
  _FormExampleState createState() => _FormExampleState();
}

class _FormExampleState extends State {
  final GlobalKey _formKey = GlobalKey();
  String _name = '';

  void _submitForm() {
    if (_formKey.currentState!.validate()) {
      _formKey.currentState!.save();
      // Process form data here
      print('Name: $_name');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Form Example'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            children: [
              TextFormField(
                decoration: InputDecoration(
                  labelText: 'Name',
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Please enter your name';
                  }
                  return null;
                },
                onSaved: (value) {
                  _name = value!;
                },
              ),
              SizedBox(height: 16.0),
              ElevatedButton(
                onPressed: _submitForm,
                child: Text('Submit'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
 

In this example, we create a simple form with a 'TextFormField' for collecting the user's name. We use the 'Form' widget and a 'GlobalKey' to manage the form state and validation. When the user submits the form, the '_submitForm' function is called, which validates and processes the form data.

Conclusion:

Handling user input is a fundamental part of building interactive Flutter apps. By using widgets like buttons, text fields, checkboxes, radio buttons, and forms, you can create engaging user interfaces that respond to user actions. Experiment with different input elements and validation techniques to meet the specific requirements of your Flutter app.