In Dart, you can perform a type check using the is and is! operators. These allow you to determine at runtime whether an object is of a particular type or is not of that type.
- The
isoperator checks if an object matches a specific type:
dynamic value = 'Hello';
if (value is String) {
print('It is a string'); // Output: It is a string
}
The is! operator checks if an object does not match a type:
dynamic value = 42;
if (value is! String) {
print('It is not a string'); // Output: It is not a string
}
Additionally, after a successful is check, Dart automatically promotes the variable’s type within that scope, so you can access type-specific properties or methods without explicit casting:
dynamic value = 'Hello';
if (value is String) {
print(value.length); // Dart knows value is a String here
}
I’ve applied type checking in Flutter projects when working with JSON parsing or dynamic API data. Often, API responses can have values that are null, String, or List. Using is and is! ensured that I only performed operations on the correct type, preventing runtime errors.
A challenge I faced was handling nullable values correctly, because type checks don’t automatically account for null. Overusing dynamic typing can also make the code verbose. A better alternative is to define strongly typed model classes and parse JSON into those models, which reduces the need for frequent type checks.
