Search code examples
flutterdartvalidationoperators

Flutter: comparison operators


I'm trying to validate a form with a comparison operator but it's giving me this error.

The operator '>' isn't defined for the type 'String'.
Try defining the operator '>'
    String fare = ''; //the value I want
    double amount = totalDistance * 0.25; //code for total distance has already been taken care of
        String amountPerPass = amount.toStringAsFixed(0);
        setState(() {
          fare = amountPerPass;
        });

This works well and i get the fare. However, I wan to use the fare to validate a form. But it's not working. Any help?

TextFormField(
validator: (value) 
{if (value!.isEmpty) 
{return ('Enter the amount per passenger');}
if (value > fare) //The error occurs here with the operator sign. How can I correct it?
{   
return ('Your price should not exceed $fare');
}
},
)

Solution

  • Firstly, use fare as double dataType(or another variable based on your need) to compare on if state.

     double fare = totalDistance * 0.25;  
    ....
    TextFormField(
      validator: (value) {
        if (value == null || value.isEmpty) {
          return ('Enter the amount per passenger');
        }
        final current = double.tryParse("${value}") ?? 0;
        if (current > fare) {
          return ('Your price should not exceed $fare');
        }