In this section, we will explore the various input and form widgets available in Flutter. These widgets are essential for creating interactive and user-friendly applications. We will cover the following topics:

  1. TextField Widget
  2. Form Widget
  3. FormField Widget
  4. Checkbox Widget
  5. Radio Button Widget
  6. Switch Widget
  7. DropdownButton Widget

  1. TextField Widget

The TextField widget is used to create a text input field. It allows users to enter and edit text.

Example:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('TextField Example')),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: TextField(
            decoration: InputDecoration(
              border: OutlineInputBorder(),
              labelText: 'Enter your name',
            ),
          ),
        ),
      ),
    );
  }
}

Explanation:

  • TextField: Creates a text input field.
  • InputDecoration: Adds decoration to the TextField, such as a border and label.

  1. Form Widget

The Form widget is a container for grouping and validating multiple form fields.

Example:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Form Example')),
        body: MyCustomForm(),
      ),
    );
  }
}

class MyCustomForm extends StatefulWidget {
  @override
  _MyCustomFormState createState() => _MyCustomFormState();
}

class _MyCustomFormState extends State<MyCustomForm> {
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          TextFormField(
            decoration: InputDecoration(
              labelText: 'Enter your name',
            ),
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Please enter some text';
              }
              return null;
            },
          ),
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 16.0),
            child: ElevatedButton(
              onPressed: () {
                if (_formKey.currentState!.validate()) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('Processing Data')),
                  );
                }
              },
              child: Text('Submit'),
            ),
          ),
        ],
      ),
    );
  }
}

Explanation:

  • Form: A container for form fields.
  • GlobalKey<FormState>: A key to uniquely identify the form and access its state.
  • TextFormField: A form field for text input with validation.
  • validator: A function to validate the input.

  1. FormField Widget

The FormField widget is a base class for form field widgets. It can be used to create custom form fields.

Example:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('FormField Example')),
        body: MyCustomFormField(),
      ),
    );
  }
}

class MyCustomFormField extends StatefulWidget {
  @override
  _MyCustomFormFieldState createState() => _MyCustomFormFieldState();
}

class _MyCustomFormFieldState extends State<MyCustomFormField> {
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          FormField<String>(
            builder: (FormFieldState<String> state) {
              return InputDecorator(
                decoration: InputDecoration(
                  labelText: 'Custom Field',
                  errorText: state.hasError ? state.errorText : null,
                ),
                child: Text('Custom Input'),
              );
            },
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Please enter some text';
              }
              return null;
            },
          ),
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 16.0),
            child: ElevatedButton(
              onPressed: () {
                if (_formKey.currentState!.validate()) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('Processing Data')),
                  );
                }
              },
              child: Text('Submit'),
            ),
          ),
        ],
      ),
    );
  }
}

Explanation:

  • FormField: A base class for form fields.
  • InputDecorator: A widget to decorate the input field.
  • FormFieldState: Manages the state of the form field.

  1. Checkbox Widget

The Checkbox widget is used to create a checkbox input.

Example:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Checkbox Example')),
        body: MyCheckbox(),
      ),
    );
  }
}

class MyCheckbox extends StatefulWidget {
  @override
  _MyCheckboxState createState() => _MyCheckboxState();
}

class _MyCheckboxState extends State<MyCheckbox> {
  bool _isChecked = false;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Checkbox(
        value: _isChecked,
        onChanged: (bool? value) {
          setState(() {
            _isChecked = value!;
          });
        },
      ),
    );
  }
}

Explanation:

  • Checkbox: Creates a checkbox input.
  • value: The current state of the checkbox.
  • onChanged: A callback function that is called when the checkbox state changes.

  1. Radio Button Widget

The Radio widget is used to create a radio button input.

Example:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Radio Button Example')),
        body: MyRadioButton(),
      ),
    );
  }
}

class MyRadioButton extends StatefulWidget {
  @override
  _MyRadioButtonState createState() => _MyRadioButtonState();
}

class _MyRadioButtonState extends State<MyRadioButton> {
  int _selectedValue = 1;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        ListTile(
          title: Text('Option 1'),
          leading: Radio<int>(
            value: 1,
            groupValue: _selectedValue,
            onChanged: (int? value) {
              setState(() {
                _selectedValue = value!;
              });
            },
          ),
        ),
        ListTile(
          title: Text('Option 2'),
          leading: Radio<int>(
            value: 2,
            groupValue: _selectedValue,
            onChanged: (int? value) {
              setState(() {
                _selectedValue = value!;
              });
            },
          ),
        ),
      ],
    );
  }
}

Explanation:

  • Radio: Creates a radio button input.
  • value: The value of the radio button.
  • groupValue: The value of the currently selected radio button in the group.
  • onChanged: A callback function that is called when the radio button state changes.

  1. Switch Widget

The Switch widget is used to create a toggle switch input.

Example:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Switch Example')),
        body: MySwitch(),
      ),
    );
  }
}

class MySwitch extends StatefulWidget {
  @override
  _MySwitchState createState() => _MySwitchState();
}

class _MySwitchState extends State<MySwitch> {
  bool _isSwitched = false;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Switch(
        value: _isSwitched,
        onChanged: (bool value) {
          setState(() {
            _isSwitched = value;
          });
        },
      ),
    );
  }
}

Explanation:

  • Switch: Creates a toggle switch input.
  • value: The current state of the switch.
  • onChanged: A callback function that is called when the switch state changes.

  1. DropdownButton Widget

The DropdownButton widget is used to create a dropdown list.

Example:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('DropdownButton Example')),
        body: MyDropdownButton(),
      ),
    );
  }
}

class MyDropdownButton extends StatefulWidget {
  @override
  _MyDropdownButtonState createState() => _MyDropdownButtonState();
}

class _MyDropdownButtonState extends State<MyDropdownButton> {
  String _selectedValue = 'One';

  @override
  Widget build(BuildContext context) {
    return Center(
      child: DropdownButton<String>(
        value: _selectedValue,
        onChanged: (String? newValue) {
          setState(() {
            _selectedValue = newValue!;
          });
        },
        items: <String>['One', 'Two', 'Three', 'Four']
            .map<DropdownMenuItem<String>>((String value) {
          return DropdownMenuItem<String>(
            value: value,
            child: Text(value),
          );
        }).toList(),
      ),
    );
  }
}

Explanation:

  • DropdownButton: Creates a dropdown list.
  • value: The current selected value.
  • onChanged: A callback function that is called when the selected value changes.
  • items: A list of items to display in the dropdown.

Conclusion

In this section, we covered various input and form widgets in Flutter, including TextField, Form, FormField, Checkbox, Radio, Switch, and DropdownButton. These widgets are essential for creating interactive and user-friendly applications. Understanding how to use these widgets will help you build robust forms and input fields in your Flutter applications.

Next, we will dive into state management in Flutter, which is crucial for managing the state of your application efficiently.

Flutter Development Course

Module 1: Introduction to Flutter

Module 2: Dart Programming Basics

Module 3: Flutter Widgets

Module 4: State Management

Module 5: Navigation and Routing

Module 6: Networking and APIs

Module 7: Persistence and Storage

Module 8: Advanced Flutter Concepts

Module 9: Testing and Debugging

Module 10: Deployment and Maintenance

Module 11: Flutter for Web and Desktop

© Copyright 2024. All rights reserved