{

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


How to Check variable type is String type in Dart and Flutter

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.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.