How to validate DropDownButton in Flutter ? (2023)

In Flutter DropDownButton is also the most important widget. We may need to select an item from the list of items but sometime we may need to put validation on DropDownButton.In this article, We will see How to validate DropDownButton in Flutter.

 

How to validate DropDownButton in Flutter: 

In Flutter when we need to validate DropDownButton we can use DropdownButtonFormField instead of the DropDownButton.

 DropdownButtonFormField({
    super.key,
    required List<DropdownMenuItem<T>>? items,
    DropdownButtonBuilder? selectedItemBuilder,
    T? value,
    Widget? hint,
    Widget? disabledHint,
    required this.onChanged,
    VoidCallback? onTap,
    int elevation = 8,
    TextStyle? style,
    Widget? icon,
    Color? iconDisabledColor,
    Color? iconEnabledColor,
    double iconSize = 24.0,
    bool isDense = true,
    bool isExpanded = false,
    double? itemHeight,
    Color? focusColor,
    FocusNode? focusNode,
    bool autofocus = false,
    Color? dropdownColor,
    InputDecoration? decoration,
    super.onSaved,
    super.validator,
    AutovalidateMode? autovalidateMode,
    double? menuMaxHeight,
    bool? enableFeedback,
    AlignmentGeometry alignment = AlignmentDirectional.centerStart,
    BorderRadius? borderRadius,
    // When adding new arguments, consider adding similar arguments to
    // DropdownButton.
  })

 

FullCode : 

Let's take an example when the user clicks on submit button then we will validate user selected a value from the  DropdownButtonFormField or not.

 

import 'package:flutter/material.dart';

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

  @override
  State<Errorgram> createState() => _ErrorgramState();
}

class _ErrorgramState extends State<Errorgram> {
  final _formKey = GlobalKey<FormState>();
  String selectedItem = "";

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        bottom: false,
        child: Scaffold(
            appBar: AppBar(
              automaticallyImplyLeading: false,
              centerTitle: true,
              title: Text(
                "Errorgram",
              ),
            ),
            body: Form(
              key: _formKey,
              child: Column(
                children: [
                  Container(
                    margin: EdgeInsets.only(right: 10, left: 10, top: 10),
                    child: DropdownButtonFormField<String>(
                      hint: Text("Select Plant"),
                      value: selectedItem == "" ? null : selectedItem,
                      isExpanded: true,
                      items: <String>[
                        'Plant 1',
                        'Plant 2',
                        'Plant 3',
                        'Plant 4'
                      ].map((String value) {
                        return DropdownMenuItem<String>(
                          value: value,
                          child: Text(value),
                        );
                      }).toList(),
                      onChanged: (value) {
                        setState(() {
                          selectedItem = value!;
                        });
                      },
                      validator: (String? value) {
                        if (value == null) {
                          return "Please select Plant";
                        }
                      },
                    ),
                  ),
                  SizedBox(
                    height: 20,
                  ),
                  ElevatedButton(
                    child: Text('Submit'),
                    onPressed: () {
                      final isValid = _formKey.currentState!.validate();
                      if (!isValid) {
                        return;
                      } else {
                        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("Success")));
                      }
                    },
                    style: ElevatedButton.styleFrom(primary: Colors.red),
                  )
                ],
              ),
            )));
  }
}

 

 

Conclusion :

We have learned How to validate DropDownButton in Flutter. We also see how to use DropdownButtonFormField instead of DropDownButton. I hope this article may help you.

Tags: