0

im trying to implement a DropdownButtonFormField to use the validator function, to show "error" message when is selected '1' but im doing something wrong because isnt working, this is my simple code, can you help me?

class ValidateDropdownButton extends StatefulWidget {
  State<ValidateDropdownButton> createState() =>
      _ValidateDropdownButtonState();
}

class _ValidateDropdownButtonState extends State<ValidateDropdownButton> {
  var data = [
    {'unit': '1', 'project': 'a'},
    {'unit': '1', 'project': 'b'},
    {'unit': '2', 'project': 'c'},
    {'unit': '2', 'project': 'd'},
  ];
  String? unit;

  Widget build(BuildContext context) {
    return Scaffold(
      body: Form(
        key: GlobalKey<FormState>(),
        autovalidateMode: AutovalidateMode.always,
        child: Column(
          children: [
            DropdownButtonFormField(
              value: unit,
              items: data
                  .map((e) => e['unit'])
                  .toSet()
                  .map((e) =>
                      DropdownMenuItem<String>(value: e, child: Text(e!)))
                  .toList(),
              onChanged: (String? value) => setState(() => unit = value),
              validator: (value) {
                if (value == '1') return 'error';
                return null;
              },
            ),
          ],
        ),
      ),
    );
  }
}

0 Answers0