Dart – Compare Strings

To compare two strings in Dart, call compareTo() on the first string and pass the second string as argument. compareTo() returns

  • negative value if first string is less than the second string.
  • zero if first string equals second string.
  • positive value if first string is greater than the second string.

The string comparison happens lexicographically.


The syntax to call compareTo() method of first string and pass the second string as argument is


where firstString and secondString are string values.



In this example, we take two strings and compare them using compareTo() method. We use if-else-if statement to check if the first string is less than, greater than, or equal to the second string.


void main() {
  var str1 = 'apple';
  var str2 = 'banana';
  var result = str1.compareTo(str2);
  if (result < 0) {
    print('"$str1" is less than "$str2".');
  } else if (result > 0) {
    print('"$str1" is greater than "$str2".');
  } else {
    print('"$str1" is equal to "$str2".');


"apple" is less than "banana".


In this Dart Tutorial, we learned how to compare two Strings, using compareTo() method of String class, with examples.