Last active
May 15, 2025 15:25
-
-
Save hectorAguero/51dcf6b8362c343a8887b5437d65fdfb to your computer and use it in GitHub Desktop.
Casting vs Parsing Map
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void main() { | |
// Sample response map | |
final response = { | |
'freezeCart': { | |
'id': '123', | |
'name': 'Sample Cart', | |
'items': ['item1', 'item2'], | |
}, | |
}; | |
// Example 1: Direct Casting | |
print('\nExample 1: Direct Casting'); | |
try { | |
final directCast = response['freezeCart'] as Map<String, Object?>; | |
print('Direct Casting: $directCast'); | |
} catch (e) { | |
print('Direct Casting Error: $e'); | |
} | |
// Example 2: Using Map<String, Object?>.from | |
print('\nExample 2: Using Map<String, Object?>.from'); | |
try { | |
final mapFrom = Map<String, Object?>.from(response['freezeCart'] as Map); | |
print('Map<String, Object?>.from: $mapFrom'); | |
} catch (e) { | |
print('Map<String, Object?>.from Error: $e'); | |
} | |
// Example 3: Using Spread Operator | |
print('\nExample 3: Using Spread Operator'); | |
try { | |
final spreadOperator = {...response['freezeCart'] as Map<String, Object?>}; | |
print('Spread Operator: $spreadOperator'); | |
} catch (e) { | |
print('Spread Operator Error: $e'); | |
} | |
// Example of an invalid response to show error handling | |
final invalidResponse = {'freezeCart': 'This is not a map'}; | |
print( | |
'\n\nExample of an invalid response to show error handling $invalidResponse\n', | |
); | |
// Direct Casting with invalid response | |
print('\nExample 1: Direct Casting with invalid response'); | |
try { | |
final directCastInvalid = | |
invalidResponse['freezeCart'] as Map<String, Object?>; | |
print('$directCastInvalid'); | |
} catch (e) { | |
print('$e'); | |
} | |
// Map<String, Object?>.from with invalid response | |
print('\nExample 2: Map<String, Object?>.from with invalid response'); | |
try { | |
final mapFromInvalid = Map<String, Object?>.from( | |
invalidResponse['freezeCart'] as Map, | |
); | |
print('$mapFromInvalid'); | |
} catch (e) { | |
print('$e'); | |
} | |
// Spread Operator with invalid response | |
print('\nExample 3: Spread Operator with invalid response'); | |
try { | |
final spreadOperatorInvalid = { | |
...invalidResponse['freezeCart'] as Map<String, Object?>, | |
}; | |
print('$spreadOperatorInvalid'); | |
} catch (e) { | |
print('$e'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment