Skip to main content

Using Form Input Widgets

1. Using Checkbox Widget

Property Values Description
value false | true Current state of the checkbox
onChanged Function(bool?) Callback when checkbox is tapped
activeColor Color Color of the checkbox when checked
checkColor Color Color of the check icon
materialTapTargetSize MaterialTapTargetSize Size of the tap target area

Example: Basic Checkbox

<Checkbox
  value: true,
  onChanged: (bool? newValue) {
    setState(() {
      value = newValue!;
    });
  },
/>

Example: Checkbox with Custom Colors

<Checkbox
  value: false,
  onChanged: (bool? newValue) {
    setState(() {
      value = newValue!;
    });
  },
  activeColor: Colors.blue,
  checkColor: Colors.white,
/>
Note: The onChanged callback must update the state to reflect the new value.

2. Using CheckboxListTile Widget

Property Values Description
title Widget? The primary content of the list tile.
subtitle Widget? The secondary content of the list tile.
value bool? The current value of the checkbox.
tristate bool If true, allows the checkbox to have a third state (indeterminate).
onChanged ValueChanged<bool>? Called when the user taps the checkbox.
controlAffinity MaterialTapTargetSize? Controls the position of the checkbox relative to the content.

Example: Basic CheckboxListTile Usage

CheckboxListTile(
  title: Text('Enable notifications'),
  value: true,
  onChanged: (bool? newValue) {
    setState(() {
      // Update the checkbox state
    });
  },
)

Example: Tristate CheckboxListTile

CheckboxListTile(
  title: Text('Select all'),
  value: null,
  tristate: true,
  onChanged: (bool? newValue) {
    setState(() {
      // Handle tristate logic
    });
  },
)

3. Using Radio Widget

Property Values Description
activeColor Color Color of the radio button when selected
fillColor MaterialStateProperty<Color> Fill color of the radio button
groupValue String The currently selected value in the group
onChanged void Function(String?) Callback when the radio button is selected
value String The value associated with this radio button

Example: Basic Radio Button Usage

class RadioExample extends StatefulWidget {
  @override
  _RadioExampleState createState() => _RadioExampleState();
}

class _RadioExampleState extends State<RadioExample> {
  String? selectedValue = 'option1';

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        RadioListTile<String>(
          title: Text('Option 1'),
          value: 'option1',
          groupValue: selectedValue,
          onChanged: (value) {
            setState(() {
              selectedValue = value;
            });
          },
        ),
        RadioListTile<String>(
          title: Text('Option 2'),
          value: 'option2',
          groupValue: selectedValue,
          onChanged: (value) {
            setState(() {
              selectedValue = value;
            });
          },
        ),
      ],
    );
  }
}
Note: Radio buttons must be grouped using the same groupValue to ensure only one can be selected at a time.

4. Using RadioListTile Widget

The RadioListTile widget in Flutter is used to display a list of radio buttons with associated labels. It's commonly used in forms where users need to select one option from a group of mutually exclusive choices.

Property Description Values
value The value of this radio button Any object that represents the selection state
groupValue The currently selected value in the group Same type as value
onChanged Callback when the radio button is selected void Function(T?)
title Primary text label for the radio button Widget
subtitle Secondary text label for the radio button Widget
enabled Whether the radio button is enabled or disabled bool

Example: Basic RadioListTile Usage

class RadioFormExample extends StatefulWidget {
  @override
  _RadioFormExampleState createState() => _RadioFormExampleState();
}

class _RadioFormExampleState extends State<RadioFormExample> {
  String? _selectedOption;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        RadioListTile<String>(
          title: Text('Option 1'),
          value: 'option1',
          groupValue: _selectedOption,
          onChanged: (value) {
            setState(() {
              _selectedOption = value;
            });
          },
        ),
        RadioListTile<String>(
          title: Text('Option 2'),
          value: 'option2',
          groupValue: _selectedOption,
          onChanged: (value) {
            setState(() {
              _selectedOption = value;
            });
          },
        ),
      ],
    );
  }
}

Example: RadioListTile with Subtitle

RadioListTile<String>(
  title: Text('Email'),
  subtitle: Text('Receive notifications via email'),
  value: 'email',
  groupValue: _selectedOption,
  onChanged: (value) {
    setState(() {
      _selectedOption = value;
    });
  },
)
Note: The RadioListTile widget is designed to be used within a group where only one radio button can be selected at a time. The groupValue must be the same for all radio buttons in the group.

5. Using Switch Widget

Property Values Description
value bool The current value of the switch.
onChanged Function(bool)? Called when the user toggles the switch.
activeColor Color The color to use for the switch's thumb when it is in the "on" position.
inactiveThumbColor Color The color to use for the switch's thumb when it is in the "off" position.
inactiveTrackColor Color The color to use for the switch's track when it is in the "off" position.
activeThumbImage ImageProvider? An image to display on the thumb when it is in the "on" position.

Example: Basic Switch Widget

Switch(
  value: isSwitched,
  onChanged: (bool newValue) {
    setState(() {
      isSwitched = newValue;
    });
  },
)

Example: Switch with Custom Colors

Switch(
  value: isSwitched,
  onChanged: (bool newValue) {
    setState(() {
      isSwitched = newValue;
    });
  },
  activeColor: Colors.blue,
  inactiveThumbColor: Colors.grey,
  inactiveTrackColor: Colors.lightBlue,
)

6. Using SwitchListTile Widget

Property Values Description
title Widget? Primary text label for the switch
subtitle Widget? Secondary text label below the title
value bool Current state of the switch (true = on, false = off)
onChanged Function(bool)? Callback when the switch is toggled
activeColor Color? Color of the switch when active
inactiveColor Color? Color of the switch when inactive
activeThumbImage ImageProvider? Custom image for the thumb when active
inactiveThumbImage ImageProvider? Custom image for the thumb when inactive

Example: Basic SwitchListTile Usage

SwitchListTile(
  title: Text('Enable notifications'),
  subtitle: Text('Receive push notifications'),
  value: notificationsEnabled,
  onChanged: (bool newValue) {
    setState(() {
      notificationsEnabled = newValue;
    });
  },
)

Example: Custom SwitchListTile with Colors

SwitchListTile(
  title: Text('Dark Mode'),
  value: isDarkMode,
  onChanged: (bool newValue) {
    setState(() {
      isDarkMode = newValue;
    });
  },
  activeColor: Colors.blue,
  inactiveColor: Colors.grey,
)
Note: SwitchListTile is a Material Design widget that combines a switch with a title and optional subtitle. It's commonly used in settings screens.

7. Using Slider Widget

Property Values Description
value double Current value of the slider. Must be between min and max.
min double Minimum value of the slider. Defaults to 0.0.
max double Maximum value of the slider. Defaults to 100.0.
divisions int Number of discrete divisions. If null, slider is continuous.
onChange ValueChanged<double> Callback when the slider value changes. Receives new value as argument.
onChangeStart ValueChanged<double> Callback when the user starts dragging the slider.
onChangeEnd ValueChanged<double> Callback when the user finishes dragging the slider.
activeColor Color Color of the active portion of the slider.
inactiveColor Color Color of the inactive portion of the slider.
thumbColor Color Color of the slider thumb (handle).

Example: Basic Slider

Slider(
  value: _currentValue,
  min: 0.0,
  max: 100.0,
  divisions: 100,
  onChanged: (double value) {
    setState(() {
      _currentValue = value;
    });
  },
)

Example: Slider with Custom Thumb

Slider(
  value: _currentValue,
  min: 0.0,
  max: 100.0,
  activeColor: Colors.blue,
  inactiveColor: Colors.grey,
  thumbColor: Colors.red,
  onChanged: (double value) {
    setState(() {
      _currentValue = value;
    });
  },
)
Note: The divisions property determines how many discrete steps the slider has. Setting it to null makes the slider continuous.

8. Using RangeSlider Widget

The RangeSlider widget in Flutter allows users to select a range of values within a specified interval. It is particularly useful for scenarios where you need to define a minimum and maximum value, such as setting age ranges or price brackets.

Property Description Values
values The current selected range values. RangeValues
min The minimum value the slider can select. double
max The maximum value the slider can select. double
divisions The number of discrete divisions for the slider. int
onChange Callback function when the range changes. ValueChanged<RangeValues>
onChanged Callback function when the range is released. ValueChanged<RangeValues>

Example: Basic RangeSlider

<RangeSlider
  values: const RangeValues(20.0, 80.0),
  min: 0.0,
  max: 100.0,
  divisions: 100,
  onChanged: (RangeValues values) {
    setState(() {
      _rangeValues = values;
    });
  },
/>

Example: RangeSlider with Labels

<RangeSlider
  values: _rangeValues,
  min: 0.0,
  max: 100.0,
  divisions: 100,
  labels: RangeLabels(_rangeValues.start.toStringAsFixed(1), _rangeValues.end.toStringAsFixed(1)),
  onChanged: (RangeValues values) {
    setState(() {
      _rangeValues = values;
    });
  },
/>

9. Using DropdownButton Widget

The DropdownButton widget in Flutter is used to create a dropdown menu that allows users to select one option from a list of items. It's commonly used for form inputs where a single selection is required.

Property Values Description
items List<DropdownMenuItem> A list of DropdownMenuItem widgets that define the options in the dropdown.
value Object? The currently selected value. If null, the dropdown will show a placeholder or no selection.
onChanged Function(Object?)? A callback function that is called when the user selects a new item. It receives the selected value as an argument.
hint Widget? A widget to display when no item is selected. Often used as a placeholder.
disabledHint Widget? A widget to display when the dropdown is disabled and no item is selected.
elevation int The elevation of the dropdown menu. Default is 8.
style TextStyle? The style to apply to the text in the dropdown.
icon Widget? A widget to display as the dropdown icon. Defaults to a downward arrow.
iconSize double? The size of the dropdown icon.
isExpanded bool If true, the dropdown will expand to fill the available space. Default is false.
isDense bool If true, the dropdown will use less vertical space. Default is false.

Example: Basic DropdownButton Usage

class MyDropdownExample extends StatefulWidget {
  @override
  _MyDropdownExampleState createState() => _MyDropdownExampleState();
}

class _MyDropdownExampleState extends State<MyDropdownExample> {
  String? _selectedValue;

  @override
  Widget build(BuildContext context) {
    return DropdownButton<String>(
      value: _selectedValue,
      hint: Text("Select an option"),
      items: <String>["Option 1", "Option 2", "Option 3"]
          .map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
      onChanged: (String? newValue) {
        setState(() {
          _selectedValue = newValue;
        });
      },
    );
  }
}

Example: DropdownButton with Custom Styling

DropdownButton<String>(
  value: _selectedValue,
  hint: Text("Choose a color", style: TextStyle(color: Colors.grey)),
  items: <String>["Red", "Green", "Blue"]
      .map<DropdownMenuItem<String>>((String value) {
    return DropdownMenuItem<String>(
      value: value,
      child: Text(value, style: TextStyle(color: Colors.black)),
    );
  }).toList(),
  onChanged: (String? newValue) {
    setState(() {
      _selectedValue = newValue;
    });
  },
  style: TextStyle(fontSize: 16, color: Colors.blue),
  iconSize: 30,
  elevation: 5,
)

10. Using DropdownButtonFormField Widget

Property Values Description
items List<DropdownMenuItem<T>> List of items to display in the dropdown
value T? Currently selected value
onChanged void Function(T?)? Callback when a new item is selected
validator FormFieldValidator<T> Validation function for form input
decoration InputDecoration? Decoration for the input field

Example: Basic DropdownButtonFormField

DropdownButtonFormField<String>(
  decoration: InputDecoration(
    labelText: 'Select Country',
    border: OutlineInputBorder(),
  ),
  value: 'US',
  items: <String>['US', 'CA', 'UK'].map((String item) {
    return DropdownMenuItem<String>(
      value: item,
      child: Text(item),
    );
  }).toList(),
  onChanged: (String? newValue) {
    setState(() {
      selectedCountry = newValue!;
    });
  },
)

Example: With Validation

final _formKey = GlobalKey<FormState>();
String? selectedCountry;

DropdownButtonFormField<String>(
  decoration: InputDecoration(
    labelText: 'Country',
    border: OutlineInputBorder(),
  ),
  value: selectedCountry,
  items: <String>['US', 'CA', 'UK'].map((String item) {
    return DropdownMenuItem<String>(
      value: item,
      child: Text(item),
    );
  }).toList(),
  validator: (String? value) {
    if (value == null || value.isEmpty) {
      return 'Please select a country';
    }
    return null;
  },
  onChanged: (String? newValue) {
    setState(() {
      selectedCountry = newValue!;
    });
  },
)

11. Using DropdownMenu Widget

Property Values Description
items List<DropdownMenuItem<T>> List of menu items to display in the dropdown
value T? The currently selected value
onChanged void Function(T?)? Callback when a new item is selected
hint Widget? Hint text shown when no item is selected
enabled bool Whether the dropdown is interactive

Example: Basic DropdownMenu

DropdownMenu<String>(
  items: [
    DropdownMenuItem(value: 'option1', child: Text('Option 1')),
    DropdownMenuItem(value: 'option2', child: Text('Option 2')),
  ],
  value: 'option1',
  onChanged: (value) {
    // Handle selection
  },
)

Example: With Hint and Validation

DropdownMenu<String>(
  items: [
    DropdownMenuItem(value: 'apple', child: Text('Apple')),
    DropdownMenuItem(value: 'banana', child: Text('Banana')),
  ],
  value: null,
  hint: Text('Select a fruit'),
  onChanged: (value) {
    if (value != null) {
      print('Selected: $value');
    }
  },
)
Note: The DropdownMenu widget is part of the newer Material 3 design system and provides a more modern and flexible approach than DropdownButton.
Warning: Ensure that items list is not empty, or the widget will throw an error.

12. Using Autocomplete Widget

The Autocomplete widget in Flutter provides a text field with suggestions that appear as the user types, allowing for quick selection of predefined values.

Property Description Values
optionsBuilder Function that returns a list of suggestions based on the input text. Future<List<T>> Function(String)
onSelected Callback invoked when a suggestion is selected. void Function(T)
fieldViewBuilder Customizes the text field used for input. Widget Function(BuildContext, TextEditingController, FocusNode)
displayStringForOption Defines how to display each option in the suggestion list. String Function(T)

Example: Basic Autocomplete Usage

class CountryAutocomplete extends StatelessWidget {
  final List<String> countries = [
    'United States',
    'Canada',
    'Mexico',
    'Brazil',
    'Argentina'
  ];

  @override
  Widget build(BuildContext context) {
    return Autocomplete<String>(
      optionsBuilder: (TextEditingValue value) {
        if (value.text.isEmpty) {
          return const Iterable<String>.empty();
        }
        return countries.where((country) =>
            country.toLowerCase().contains(value.text.toLowerCase()));
      },
      onSelected: (String selection) {
        print('Selected: $selection');
      },
      displayStringForOption: (String option) => option,
    );
  }
}
Note: The Autocomplete widget is ideal for forms where users need to select from a predefined list of options, enhancing usability and reducing input errors.

Was this article helpful?