1

This is my dropdownlist for start time. I wanted to validate the dropdownlist under the condition that if the user chooses the end hour less than the start date, it will show an error. What are the steps in implementing that?

Flexible(
    child: DropdownButtonFormField(
  hint: _selectedStartHour != null
      ? Text(_selectedStartHour)
      : const Text(''),
  decoration: const InputDecoration(
    labelText: 'Hours',
    filled: true,
    fillColor: Colors.white,
    border:
        OutlineInputBorder(borderSide: BorderSide(color: Colors.grey)),
  ),
  icon: const Icon(Icons.arrow_drop_down),
  iconSize: 24,
  elevation: 16,
  items: hours.map<DropdownMenuItem>((String value) {
    return DropdownMenuItem(value: value, child: Text(value));
  }).toList(),
  onChanged: (data) {
    setState(() {
      _selectedStartHour = data;
      print(_selectedStartHour);
    });
  },
  validator: (value) => value == null ? 'Please select hours' : null,
)),

This is my dropdownlist for end time.

Flexible(
    child: DropdownButtonFormField(
  hint:
      _selectedEndHour != null ? Text(_selectedEndHour) : const Text(''),
  decoration: const InputDecoration(
    labelText: 'Hours',
    filled: true,
    fillColor: Colors.white,
    border:
        OutlineInputBorder(borderSide: BorderSide(color: Colors.grey)),
  ),
  icon: const Icon(Icons.arrow_drop_down),
  iconSize: 24,
  elevation: 16,
  items: hours.map<DropdownMenuItem>((String value) {
    return DropdownMenuItem(value: value, child: Text(value));
  }).toList(),
  onChanged: (data) {
    setState(() {
      _selectedEndHour = data;
      print(_selectedEndHour);
    });
  },
)),

This is my list to populate my start and end time.

 List<String> hours = [
    '1',
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    '10',
    '11',
    '12'
  ];

My _selectedStartHour and _selectedEndHour is a String

  String _selectedStartHour = '2';
  String _selectedEndHour = '3';
Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
wuuyungwuu
  • 83
  • 13

1 Answers1

0

For the endHour validator, the logic can be

validator: (value) {
  if (_selectedStartHour == null) return "Select Start hour";

  final startHour = int.tryParse(_selectedStartHour) ?? 0;
  final endHour = int.tryParse(_selectedEndHour) ?? 0;
  if (startHour < endHour) {
    return "End hour must be after start hour";
  }
},
Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
  • Glad to help, Also I think you can directly use int instead of string like `DropdownButtonFormField`. This way, you don't have to parse to int. DropdownMenuItem value also will be int type in this case. – Md. Yeasin Sheikh Dec 16 '22 at 13:27
  • 1
    I see. Then I would need to change my List to List – wuuyungwuu Dec 16 '22 at 13:36