in flutter using “as Map” vs using “ is Map” ? Whats the difference between them
#flutter
Answer
Overview
In Dart,
text
astext
is- checks if an object is of a specific type (returnstext
is)textbool - casts an object to a specific type (returns the casted object or throws error)text
as
textis
Operator — Type Check
text
isChecks if an object is an instance of a type. Returns
text
truetext
falseSyntax
dartobject is Type
Examples
dartdynamic value = 'Hello'; if (value is String) { print('It is a String'); // ✅ Prints } if (value is int) { print('It is an int'); // ❌ Does not print } // Negation if (value is! int) { print('It is NOT an int'); // ✅ Prints }
Type Promotion
After an
text
isdartdynamic value = 'Hello'; if (value is String) { print(value.length); // ✅ value is promoted to String print(value.toUpperCase()); // ✅ No cast needed }
Use Cases
dart// Check before using type-specific methods dynamic data = fetchData(); if (data is Map) { print(data['key']); } if (data is List) { print(data.length); }
textas
Operator — Type Cast
text
asExplicitly casts an object to a specific type. Throws an error if the cast fails.
Syntax
dartobject as Type
Examples
dartdynamic value = 'Hello'; String str = value as String; // ✅ Works (value is String) print(str.length); // ✅ 5 int num = value as int; // ❌ CastError! (value is not int)
Safe Cast with Nullable Types
dartdynamic value = 42; String? str = value as String?; // ✅ No error (returns null if cast fails) print(str); // null
Use Cases
dart// Casting JSON values Map<String, dynamic> json = {'name': 'Alice', 'age': 25}; String name = json['name'] as String; // ✅ Explicit cast int age = json['age'] as int; // ✅ // Casting in collections List<dynamic> items = [1, 2, 3]; List<int> numbers = items.cast<int>(); // ✅ Cast entire list
Comparison: textis
vs textas
text
istext
as| Feature | text | text |
|---|---|---|
| Purpose | Check type | Cast type |
| Returns | text | Casted object |
| Error if wrong | ❌ No (returns false) | ✅ Yes (throws CastError) |
| Type promotion | ✅ Yes (automatic) | ❌ No |
| Use case | Safe type checking | Explicit casting |
When to Use Which
Use textis
(Type Check)
text
is✅ When you want to check if an object is a certain type before using it.
dartdynamic data = fetchData(); if (data is Map) { print(data['key']); // ✅ Safe }
✅ When you want to avoid errors by checking first.
dartif (value is String) { print(value.toUpperCase()); // ✅ No cast needed (type-promoted) }
Use textas
(Type Cast)
text
as✅ When you're certain of the type and need an explicit cast.
dartMap<String, dynamic> json = {'name': 'Alice'}; String name = json['name'] as String; // ✅ Explicit
✅ When dealing with JSON or dynamic data.
dartList<dynamic> data = jsonDecode(response.body); List<Map<String, dynamic>> items = data.cast<Map<String, dynamic>>();
Safe Casting Pattern
Combine
text
istext
asdartdynamic value = fetchData(); // ❌ Unsafe cast (may throw) String name = value as String; // ✅ Safe cast with check if (value is String) { String name = value; // ✅ Type-promoted print(name.toUpperCase()); } // ✅ Alternative: Safe cast with nullable String? name = value is String ? value as String : null;
JSON Parsing Example
Using textis
text
isdartMap<String, dynamic> json = {'name': 'Alice', 'age': 25}; if (json['name'] is String) { String name = json['name']; // ✅ Type-promoted print(name.toUpperCase()); }
Using textas
text
asdartMap<String, dynamic> json = {'name': 'Alice', 'age': 25}; String name = json['name'] as String; // ✅ Explicit cast int age = json['age'] as int;
Nullable Cast
dartMap<String, dynamic> json = {'name': null}; String? name = json['name'] as String?; // ✅ null if key is null print(name ?? 'Guest'); // Guest
Map Example
Problem
dartdynamic data = {'key': 'value'}; // ❌ Cannot call [] on dynamic // print(data['key']); // ✅ Use is if (data is Map) { print(data['key']); // ✅ Works } // ✅ Use as Map<String, dynamic> map = data as Map<String, dynamic>; print(map['key']); // ✅ Works
List Example
Using textis
text
isdartdynamic data = [1, 2, 3]; if (data is List) { print(data.length); // ✅ Type-promoted to List }
Using textas
text
asdartdynamic data = [1, 2, 3]; List<int> numbers = data as List<int>; // ✅ Explicit cast print(numbers.first); // 1
Common Mistakes
Mistake 1: Using textas
Without Checking
text
asdartdynamic value = 42; // ❌ Throws CastError String str = value as String; // ✅ Check first if (value is String) { String str = value; }
Mistake 2: Forgetting Type Promotion
dartdynamic value = 'Hello'; if (value is String) { // ✅ No need for cast (type-promoted) print(value.toUpperCase()); // ❌ Redundant cast print((value as String).toUpperCase()); }
Mistake 3: Not Handling Null
dartdynamic value = null; // ❌ CastError (null is not String) String str = value as String; // ✅ Nullable cast String? str = value as String?;
Best Practices
dart// ✅ Use is for safe type checking if (value is String) { print(value.length); // Type-promoted } // ✅ Use as for explicit casts (when you're sure) String name = json['name'] as String; // ✅ Combine is and as for safety if (value is Map) { Map<String, dynamic> map = value; // No cast needed } // ❌ Avoid blind casts // String str = value as String; ❌ May crash // ✅ Use nullable casts for optional values String? name = json['name'] as String?;
Summary
| Operator | Purpose | Returns | Throws Error? | Type Promotion |
|---|---|---|---|---|
text | Type check | text | ❌ No | ✅ Yes |
text | Type cast | Casted object | ✅ Yes (if wrong) | ❌ No |
When to use:
- Use to check types safely (preferred)text
is - Use to cast types explicitly (when you're certain)text
as
Example workflow:
dart// 1. Check type with is if (data is Map) { // 2. Use directly (type-promoted) print(data['key']); } // OR // 1. Cast with as (if you're sure) Map<String, dynamic> map = data as Map<String, dynamic>; print(map['key']);
Learn more: Dart Type System