Dart Type Test Operators
Dart Type Test Operators
Type test operators are used to check the type of a value when the program runs.
| Operator | Description | Example |
|---|---|---|
is | Returns true if the value has the type | x is int |
is! | Returns true if the value does not have the type | x is! int |
as | Treats the value as the type (a type cast) | x as String |
In the examples on this page, we use the type Object.
An Object variable can hold any value that is not null, like a number, a string or a bool.
The is Operator
The is operator returns true if a value has a type:
Example
void main() {
Object value = 42;
print(value is int);
print(value is String);
print(value is num);
}
Try it Yourself »
Result:
true
false
true
value is num is also true, because every int is also a num.
The is! Operator
The is! operator is the opposite of is.
It returns true if a value does not have a type:
Example
void main() {
Object value = 'Hello';
print(value is! int);
print(value is! String);
}
Try it Yourself »
Result:
true
false
Type Promotion with is
When you check a type with is in an if statement, Dart remembers the result inside the block.
This is called type promotion, the same as with null checks.
In the example below, toUpperCase() only exists on strings, but we can use it because Dart knows that value is a String inside the block:
Example
void main() {
Object value = 'dart';
if (value is String) {
print(value.toUpperCase());
print(value.length);
}
}
Try it Yourself »
Result:
DART
4
Without the check, the program does not run, because an Object has no toUpperCase() method:
Result:
main.dart:3:15: Error: The method 'toUpperCase' isn't defined for the type 'Object'.
- 'Object' is from 'dart:core'.
Try correcting the name to the name of an existing method, or defining a method named 'toUpperCase'.
print(value.toUpperCase());
^^^^^^^^^^^
The as Operator
The as operator tells Dart to treat a value as a specific type.
This is called a type cast:
Example
void main() {
Object value = 'dart';
String text = value as String;
print(text.toUpperCase());
}
Try it Yourself »
Result:
DART
If the value does not have that type, the program stops with an error when it runs:
Example
void main() {
Object value = 42;
String text = value as String;
print(text);
}
Try it Yourself »
Result:
Unhandled exception:
type 'int' is not a subtype of type 'String' in type cast
Tip: An is check is safer than as, because it never stops the program.
Use as only when you are sure about the type.
The as operator does not convert values.
To turn the string '42' into a number, use int.parse() from the Type Conversion chapter.