Check if selectedEndHour is more than selectedStartHour

Issue

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';

Solution

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";
  }
},

Answered By – Yeasin Sheikh

Answer Checked By – Terry (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *