35 Nullable Data fron API?
Q: Regarding Dart’s null awareness, If I write code that waiting to receive JSON data from external API, how do I handle the logic of this code?
When handling JSON data from external APIs in Dart, your null safety approach should match your confidence level about the data. Here’s how to handle each scenario:
35.1 Scenario 1: Very High Confidence API Data is NOT Null
Non-nullable type (String
):
// Use when you're certain the field exists and has a value
String name = jsonData['name']; // Will throw if null
Nullable type (String?
):
// Still safe, but adds unnecessary null checks later
String? name = jsonData['name'];
String displayName = name ?? 'Unknown'; // Need to handle null
late
variable:
// Good for class fields when you'll assign after construction
class User {
late String name; // Will be assigned in parseJson()
void parseJson(Map<String, dynamic> json) {
= json['name']; // Throws if null, but you're confident it won't be
name }
}
Null assertion operator (!
):
// Use when JSON might be dynamic but you're confident about the value
String name = jsonData['name']!; // Explicit "I know this isn't null"
35.2 Scenario 2: API Data CAN Be Null
Non-nullable type (String
):
// DON'T use - will cause runtime errors
String name = jsonData['name']; // ❌ Dangerous if null
Nullable type (String?
):
// ✅ BEST approach - handle null safely
String? name = jsonData['name'];
String displayName = name ?? 'No name provided';
late
variable:
// ❌ DON'T use - defeats null safety purpose
late String name; // Will throw at runtime if assigned null
Null assertion operator (!
):
// ❌ DON'T use - will crash if null
String name = jsonData['name']!; // Dangerous assumption
35.3 Recommended Patterns
For highly reliable APIs:
class User {
final String id;
final String email;
.fromJson(Map<String, dynamic> json)
User: id = json['id'],
= json['email'];
email }
For APIs that might have null values:
class User {
final String id;
final String? nickname; // Optional field
final String email;
.fromJson(Map<String, dynamic> json)
User: id = json['id'],
= json['nickname'], // Can be null
nickname = json['email'] ?? 'unknown@example.com'; // Provide fallback
email }
Defensive parsing with validation:
.fromJson(Map<String, dynamic> json) {
User// Validate required fields
final id = json['id'] as String?;
if (id == null) throw ArgumentError('User ID cannot be null');
return User(
: id,
id: json['nickname'] as String?, // Explicitly nullable
nickname: json['email'] as String? ?? 'unknown@example.com',
email
);}
The key principle: match your null safety strategy to your actual confidence level about the API data, not your hopes about it.