Dart| Flutter: How to check the variable type is a String or not| Flutter By Example

This is a simple post to check variable is of a String type.

The ‘is’ operator in Dart checks the type of a variable at runtime and returns true or false depending on whether the variable has a predefined type. String data in dart can be created with variables of type String or dynamic type. stringvariable is String returns true if the variable is a string.

How to check given variable type is a String in Dart/Flutter

the dynamic type also holds any type of data.

if you assign string data to a dynamic type, It returns true for String dynamic types.

void main() {
  var str = "abc";
  print(str is String); //true
  if (str is String) {
    print(str); //eric
  }
}

Output:

true
eric

In the below example, dynamic types stores the string and int types.

It returns

  • true for String and dynamic types for a dynamic String variable
  • false for String types for a dynamic int value
void main() {
  dynamic str = "abc";
  dynamic variable = 123;

  print(str is String); //true
  print(str is dynamic); //true
  print(variable is String); //false
}

Conclusion

Checks a string variable type for variable declaration with string and dynamic type using is the operator.