Dart| Flutter How to: Check strings are equal or not Example
This tutorial shows how to compare whether two strings are equal or not Dart or Flutter.
Dart does not provide the isEquals (java) method to compare methods for equality.
`String equals compare the same characters in the order of both strings are equal.
Since String
is an immutable object, Once you create a string
object, does not allow you to modify the string, however, if you append to an existing string
, it creates a new string with the result, and the Original string also exists in memory.
String values of the same value create two references for the same string object.
For example, Given two strings
String str1 = 'one';
String str2 = 'two';
String str3 = 'one';
Above the program, two objects (one, two) are created in memory, str1 and str3 are referred to the same object (one), and str2 reference is pointed to another object(two).
String equality check two string values are equal (str1,str2) returns true.
It provides two ways to check string’s values are equal or not.
- double equal operator(
==
): Returns true if both strings are the same set of characters, Else return false compareTo
method :- returns
0
if both strings are equal, else returns non-zero number - returns
negative number
(-1) if first is ordered before second string - returns
positive number
(1), if the first is ordered after the second string.
- returns
Similarly, two string references are checked using the identical
method which checks two references pointed to the same object in memory.
How to compare if Strings are equal or not in dart/flutter?
==
checks two string object holds the same set of character Since it returns boolean values, useful in a conditional expression such as if.
compareTo() function
always returns a numeric value, again one more step (result==0) is required to check for string equality.
Both ways It does not check for string null safety.
identical()
in string checks whether two variables hold the same object in memory or not.
void main() {
print("one" == "one"); // true
print("one" == "ONE"); // false
print("one".compareTo("one")); // 0
print("one".compareTo("two")); // -1
String str1 = 'one';
String str2 = 'two';
String str3 = 'one';
print(identical(str1, str2)); // false
print(identical(str1, str3)); // true
}
Conclusion
To summarize, We can compare strings using double equal, compareTo, and identical methods.