Exploring Other Input Widgets (Checkbox, Radio, Slider, Switch) in Flutter

Flutter provides a rich set of input widgets that enable developers to collect various types of data from users. In addition to the standard text fields, Flutter offers a variety of other input widgets such as Checkbox, Radio, Slider, and Switch. These widgets are essential for creating interactive and user-friendly interfaces. In this article, we’ll explore these input widgets in detail with practical examples.

Overview of Flutter Input Widgets

Flutter’s input widgets allow users to interact with applications by providing input through different controls. Here’s a brief introduction to the widgets we’ll cover:

  • Checkbox: Allows users to select one or more options from a list.
  • Radio: Enables users to select one option from a mutually exclusive set.
  • Slider: Provides a way for users to select a value from a continuous range.
  • Switch: An on/off toggle control.

Checkbox in Flutter

A Checkbox is a widget that allows the user to select one or more items from a set of options. It is represented by a small square that can be checked or unchecked.

Basic Checkbox Example

Here’s how to implement a basic checkbox in Flutter:

import 'package:flutter/material.dart';

class CheckboxExample extends StatefulWidget {
  const CheckboxExample({Key? key}) : super(key: key);

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

class _CheckboxExampleState extends State {
  bool isChecked = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Checkbox Example'),
      ),
      body: Center(
        child: Checkbox(
          value: isChecked,
          onChanged: (bool? newValue) {
            setState(() {
              isChecked = newValue ?? false;
            });
          },
        ),
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(home: CheckboxExample()));
}

In this example:

  • isChecked is a boolean variable that holds the state of the checkbox.
  • The Checkbox widget’s value is bound to isChecked.
  • The onChanged function updates the isChecked variable when the checkbox is tapped.

Checkbox with a Label

To provide a label with a checkbox, you can use a Row and a GestureDetector:

import 'package:flutter/material.dart';

class CheckboxWithLabelExample extends StatefulWidget {
  const CheckboxWithLabelExample({Key? key}) : super(key: key);

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

class _CheckboxWithLabelExampleState extends State {
  bool isChecked = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Checkbox with Label Example'),
      ),
      body: Center(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Checkbox(
              value: isChecked,
              onChanged: (bool? newValue) {
                setState(() {
                  isChecked = newValue ?? false;
                });
              },
            ),
            GestureDetector(
              onTap: () {
                setState(() {
                  isChecked = !isChecked;
                });
              },
              child: const Text('Check me'),
            ),
          ],
        ),
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(home: CheckboxWithLabelExample()));
}

In this example, tapping the text label toggles the checkbox state, providing an enhanced user experience.

Radio Button in Flutter

A Radio button is a widget that allows the user to select one option from a set of mutually exclusive options. Radio buttons are typically displayed in a group, and only one button can be selected at a time.

Basic Radio Button Example

Here’s how to implement a radio button group in Flutter:

import 'package:flutter/material.dart';

enum BestLanguage { dart, java, kotlin }

class RadioButtonExample extends StatefulWidget {
  const RadioButtonExample({Key? key}) : super(key: key);

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

class _RadioButtonExampleState extends State {
  BestLanguage? _selectedLanguage = BestLanguage.dart;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Radio Button Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ListTile(
              title: const Text('Dart'),
              leading: Radio(
                value: BestLanguage.dart,
                groupValue: _selectedLanguage,
                onChanged: (BestLanguage? value) {
                  setState(() {
                    _selectedLanguage = value;
                  });
                },
              ),
            ),
            ListTile(
              title: const Text('Java'),
              leading: Radio(
                value: BestLanguage.java,
                groupValue: _selectedLanguage,
                onChanged: (BestLanguage? value) {
                  setState(() {
                    _selectedLanguage = value;
                  });
                },
              ),
            ),
            ListTile(
              title: const Text('Kotlin'),
              leading: Radio(
                value: BestLanguage.kotlin,
                groupValue: _selectedLanguage,
                onChanged: (BestLanguage? value) {
                  setState(() {
                    _selectedLanguage = value;
                  });
                },
              ),
            ),
            Text('Selected Language: ${_selectedLanguage?.name ?? 'None'}'),
          ],
        ),
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(home: RadioButtonExample()));
}

In this example:

  • BestLanguage is an enum that defines the available options.
  • _selectedLanguage is a variable that holds the currently selected value.
  • Each Radio widget is associated with a specific BestLanguage value.
  • When a radio button is tapped, the onChanged function updates _selectedLanguage.

Slider in Flutter

A Slider is a widget that allows the user to select a value from a continuous range by sliding a thumb along a track. It’s useful for adjusting values such as volume, brightness, or font size.

Basic Slider Example

Here’s how to implement a basic slider in Flutter:

import 'package:flutter/material.dart';

class SliderExample extends StatefulWidget {
  const SliderExample({Key? key}) : super(key: key);

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

class _SliderExampleState extends State {
  double _currentValue = 20;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Slider Example'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Slider(
              value: _currentValue,
              min: 0,
              max: 100,
              divisions: 5,
              label: _currentValue.round().toString(),
              onChanged: (double value) {
                setState(() {
                  _currentValue = value;
                });
              },
            ),
            Text('Current Value: ${_currentValue.round()}'),
          ],
        ),
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(home: SliderExample()));
}

In this example:

  • _currentValue holds the current value of the slider.
  • The Slider widget is configured with a minimum value of 0, a maximum value of 100, and divisions to snap to.
  • The onChanged function updates _currentValue as the slider is moved.

Switch in Flutter

A Switch is a widget that represents an on/off toggle control. It is often used to represent a binary choice, such as enabling or disabling a setting.

Basic Switch Example

Here’s how to implement a basic switch in Flutter:

import 'package:flutter/material.dart';

class SwitchExample extends StatefulWidget {
  const SwitchExample({Key? key}) : super(key: key);

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

class _SwitchExampleState extends State {
  bool _isSwitched = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Switch Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Switch(
              value: _isSwitched,
              onChanged: (bool value) {
                setState(() {
                  _isSwitched = value;
                });
              },
              activeTrackColor: Colors.lightGreenAccent,
              activeColor: Colors.green,
            ),
            Text(_isSwitched ? 'Switch is ON' : 'Switch is OFF'),
          ],
        ),
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(home: SwitchExample()));
}

In this example:

  • _isSwitched is a boolean variable that holds the state of the switch.
  • The Switch widget’s value is bound to _isSwitched.
  • The onChanged function updates _isSwitched when the switch is toggled.
  • The activeTrackColor and activeColor properties customize the appearance of the switch when it’s in the ON state.

Conclusion

Flutter provides a versatile set of input widgets beyond just text fields. The Checkbox, Radio, Slider, and Switch widgets enable developers to create more engaging and interactive user interfaces. Understanding and utilizing these widgets effectively can significantly enhance the usability and user experience of Flutter applications. Each widget serves a unique purpose in data collection and interaction, making them valuable tools for Flutter developers.