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) {
    name = json['name']; // Throws if null, but you're confident it won't be
  }
}

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