Search code examples
fluttervalidationif-statementtogglebutton

How to validate "ToggleButton" in flutter?


As It seems there is no built-in validatior() for ToggleButton I tried to do something like following inside an ElevatedButton():

          onPressed: () {
            print('this is _selectedOptions: $_selectedOptions');
            if (_selectedOptions == [false, false, false]) {
              const SnackBar(
                duration: Duration(seconds: 5),
                content:
                    Text('You should select at least 1 option '),
              );
            } 
          }

And I see this is _selectedOptions: [false, false, false] prints out, but it doesn't go into the if statement I don't know why?

Please let me know why it doesn't go into the if statement, also if there is a better way of validating ToggleButton ?


Solution

  • You could change if statement.

    From

    if (_selectedOptions == [false, false, false])
    

    To

    if (!_selectedOptions.contains(true))
    

    It's because of Dart's characteristic, check below.

    https://api.flutter.dev/flutter/dart-core/List/operator_equals.html

    "the equality comparison does not compare the elements of the two lists."