Menu

Flutter JSON Parsing: fromJson, Null Safety and Code Generation
📰

Flutter JSON Parsing: fromJson, Null Safety and Code Generation

DEV Community: mobile·Muhammad Naeem·17 days ago
#6PHTOlP6
#devtomobile#devto#dev#json#string
Long article (3299 words) — no AI summary yet.
Reading 0:00
15s threshold

Almost every Flutter app talks to an API, and almost every API speaks JSON. Dart has no reflection in Flutter, so you can't hand a JSON string to a library and get a typed object back by magic. You either write the mapping yourself or generate it.

This post covers both, in the order you'll meet them: jsonDecode , a hand-written model, the null safety traps, nested objects and lists, json_serializable , freezed , and the error messages that show up when something doesn't match.

Step 1: jsonDecode gives you dynamic data

jsonDecode from dart:convert turns a JSON string into plain Dart values: Map<String, dynamic> for objects, List<dynamic> for arrays, and String , int , double , bool or null for the rest.

import 'dart:convert' ;

void main ( ) { const body = '{"id": 7, "name": "Ayesha", "email": null}' ; final data = jsonDecode ( body ) as Map < String , dynamic > ; print ( data [ 'name' ] ) ; // Ayesha print ( data [ 'id' ] .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.