JSON is a data format, not a guarantee about the response. A field can be missing, null or a different type from what you expected. Convert external data to a model before the widget needs it.
The FlutterFever JSON-to-Dart tool can draft model fields. Review the generated types against malformed and missing data; generation does not replace boundary validation.
Parse a small response
import 'dart:convert';
class ReadingTip {
const ReadingTip(this.title, this.minutes);
final String title;
final int minutes;
factory ReadingTip.fromJson(Map<String, dynamic> json) {
final title = json['title'];
final minutes = json['minutes'];
if (title is! String || minutes is! int || minutes < 0) {
throw const FormatException('Invalid reading tip');
}
return ReadingTip(title, minutes);
}
}
void main() {
final raw = jsonDecode('{"title":"Constraints first","minutes":8}');
if (raw is! Map<String, dynamic>) {
throw const FormatException('Expected a JSON object');
}
final tip = ReadingTip.fromJson(raw);
print('${tip.title}: ${tip.minutes} minutes');
}Separate responsibilities
A network client handles the request and status code. A parser validates the payload. A repository can coordinate data access. A widget renders the resulting state.
These boundaries do not require a large folder tree. Start with clear functions and types, then separate files as the feature grows.
Be deliberate about defaults
Silently turning an invalid price into zero can be worse than surfacing an error. A missing optional subtitle may reasonably become an empty string. Choose defaults based on meaning, not convenience.
Validate meaning before creating the model
jsonDecode can successfully parse a syntactically valid document whose fields are wrong for your feature. The factory therefore checks that title is a string and minutes is a non-negative integer before constructing ReadingTip.
This creates a useful boundary: widgets that receive a ReadingTip can work with its contract rather than repeating map lookups and type checks throughout build methods. A parser failure should become a deliberate feature error, not silently turn invalid data into an apparently empty result.
Test missing keys, nulls, wrong types and invalid numeric ranges. Then use the repository architecture example to keep transport and parsing outside the interface. The Dart model lesson explains the class and constructor mechanics independently.
Try it yourself
Change minutes to a string in the JSON. Confirm the parser rejects it. Then add an optional author field and decide how the interface should represent its absence.