In Dart, is and as are type operators used for
type checking and type casting. Think of
is as asking "Is this object of this type?" and
as as saying "Treat this object as that type".
is — Type Checking
Use is when you want to check whether an object is a specific
type. The result is a boolean (true or false).
// Example: is operator
void main() {
var data = 'Hello Dart';
print(data is String); // true
print(data is int); // false
}
There's also is! which checks the opposite (object is not of
that type):
print(data is! String); // false
as — Casting
Use as to cast (convert) an object to a specific type. It's
common to use is first to make sure the cast is safe.
// Example: as operator
void main() {
dynamic data = 'Hello Dart';
String text = data as String; // cast to String
print(text.toUpperCase()); // HELLO DART
}
Warning: If you cast to the wrong type, Dart throws a TypeError.
// This will throw a TypeError:
dynamic number = 42;
String text = number as String; // runtime error
Combining is and as
To avoid runtime errors, check the type first with is, then cast:
void main() {
dynamic data = 'Hello Dart';
if (data is String) {
// inside this block, Dart already treats `data` as String for type promotion
print(data.length); // safe
// you could still explicitly cast:
String text = data as String;
print(text.toUpperCase());
}
}
Note: Dart performs type promotion in many cases, so once you
check data is String inside the if, you often
don't need an explicit as cast.
Quick Reference
| Operator | Purpose | Result |
|---|---|---|
is |
Check if an object is of a type | true / false |
is! |
Check if an object is NOT of a type | true / false |
as |
Cast object to a type (may throw at runtime if wrong) | Typed object or TypeError |
Practical Tips
- Prefer type-safe code (use strong typing) to minimize casts.
- Use
isbeforeasif the source might be multiple types. - Take advantage of Dart's type promotion to reduce explicit casts.
0 Comments:
Posting Komentar