Question #133EasyFlutter Basics

in flutter using “as Map” vs using “ is Map” ? Whats the difference between them

#flutter

Answer

Overview

In Dart,

text
as
and
text
is
are both type-related operators, but they serve different purposes:

  • text
    is
    checks if an object is of a specific type (returns
    text
    bool
    )
  • text
    as
    casts an object to a specific type (returns the casted object or throws error)

text
is
Operator — Type Check

Checks if an object is an instance of a type. Returns

text
true
or
text
false
.

Syntax

dart
object is Type

Examples

dart
dynamic 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
is
check, Dart automatically type-promotes the variable.

dart
dynamic 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);
}

text
as
Operator — Type Cast

Explicitly casts an object to a specific type. Throws an error if the cast fails.

Syntax

dart
object as Type

Examples

dart
dynamic 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

dart
dynamic 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:
text
is
vs
text
as

Feature
text
is
text
as
PurposeCheck typeCast type
Returns
text
bool
(true/false)
Casted object
Error if wrong❌ No (returns false)✅ Yes (throws CastError)
Type promotion✅ Yes (automatic)❌ No
Use caseSafe type checkingExplicit casting

When to Use Which

Use
text
is
(Type Check)

✅ When you want to check if an object is a certain type before using it.

dart
dynamic data = fetchData();

if (data is Map) {
  print(data['key']); // ✅ Safe
}

✅ When you want to avoid errors by checking first.

dart
if (value is String) {
  print(value.toUpperCase()); // ✅ No cast needed (type-promoted)
}

Use
text
as
(Type Cast)

✅ When you're certain of the type and need an explicit cast.

dart
Map<String, dynamic> json = {'name': 'Alice'};
String name = json['name'] as String; // ✅ Explicit

✅ When dealing with JSON or dynamic data.

dart
List<dynamic> data = jsonDecode(response.body);
List<Map<String, dynamic>> items = data.cast<Map<String, dynamic>>();

Safe Casting Pattern

Combine

text
is
and
text
as
for safety.

dart
dynamic 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
text
is

dart
Map<String, dynamic> json = {'name': 'Alice', 'age': 25};

if (json['name'] is String) {
  String name = json['name']; // ✅ Type-promoted
  print(name.toUpperCase());
}

Using
text
as

dart
Map<String, dynamic> json = {'name': 'Alice', 'age': 25};

String name = json['name'] as String; // ✅ Explicit cast
int age = json['age'] as int;

Nullable Cast

dart
Map<String, dynamic> json = {'name': null};

String? name = json['name'] as String?; // ✅ null if key is null
print(name ?? 'Guest'); // Guest

Map Example

Problem

dart
dynamic 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
text
is

dart
dynamic data = [1, 2, 3];

if (data is List) {
  print(data.length); // ✅ Type-promoted to List
}

Using
text
as

dart
dynamic data = [1, 2, 3];

List<int> numbers = data as List<int>; // ✅ Explicit cast
print(numbers.first); // 1

Common Mistakes

Mistake 1: Using
text
as
Without Checking

dart
dynamic value = 42;

// ❌ Throws CastError
String str = value as String;

// ✅ Check first
if (value is String) {
  String str = value;
}

Mistake 2: Forgetting Type Promotion

dart
dynamic 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

dart
dynamic 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

OperatorPurposeReturnsThrows Error?Type Promotion
text
is
Type check
text
bool
❌ No✅ Yes
text
as
Type castCasted object✅ Yes (if wrong)❌ No

When to use:

  • Use
    text
    is
    to check types safely (preferred)
  • Use
    text
    as
    to cast types explicitly (when you're certain)

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