<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Flutter JSON Parsing: fromJson, Null Safety and Code Generation]]></title><description><![CDATA[Flutter JSON Parsing: fromJson, Null Safety and Code Generation]]></description><link>https://neemii.hashnode.dev</link><image><url>https://cdn.hashnode.com/uploads/logos/6afe88d80a8396bd81928ac1/5cdc051f-8be5-485a-939b-3b30a61b9431.png</url><title>Flutter JSON Parsing: fromJson, Null Safety and Code Generation</title><link>https://neemii.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Wed, 25 Nov 2026 12:30:53 GMT</lastBuildDate><atom:link href="https://neemii.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Flutter AI Chat Without Exposing Your OpenAI API Key]]></title><description><![CDATA[Add a ChatGPT-style chat to a Flutter app without shipping your API key: a small Dart backend proxy, per-user rate limits, streaming replies.]]></description><link>https://neemii.hashnode.dev/flutter-ai-chat-without-exposing-your-openai-api-key</link><guid isPermaLink="true">https://neemii.hashnode.dev/flutter-ai-chat-without-exposing-your-openai-api-key</guid><category><![CDATA[Flutter]]></category><category><![CDATA[AI]]></category><category><![CDATA[Security]]></category><category><![CDATA[Dart]]></category><dc:creator><![CDATA[Muhammad Naeem]]></dc:creator><pubDate>Sun, 22 Nov 2026 10:17:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6afe88d80a8396bd81928ac1/dff95109-2618-4a8d-8836-6817ae068ad8.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>Short answer:</strong> Never put an OpenAI, Gemini or Claude API key inside a Flutter app, because anyone can pull it out of the install file. Put a small backend in between: the app calls your server, your server holds the key, checks the user and their limits, calls the AI provider and streams the answer back. If you don't want to run a server, Firebase AI Logic is a managed alternative.</p>
<p>Adding an AI chat screen to a Flutter app looks like a one-afternoon job. You grab an API key from OpenAI or Google, call the chat endpoint with <code>package:http</code>, and print the reply. It works on your phone, so you ship it.</p>
<p>Then someone pulls the key out of your app and runs their own traffic on your account. You find out from the bill.</p>
<p>This post shows the setup I'd use instead: the key lives on a small server you control, the app talks to that server with the signed-in user's token, and the server handles rate limits, the model choice and the cost caps. The reply still streams into the chat UI word by word. All the Dart code below (the proxy and the client) was run locally against a fake upstream server, so it does what it says.</p>
<h2>Why an API key inside your app is not secret</h2>
<p>Anything you put in an app binary goes to every person who installs it. An APK or IPA is an archive. People unzip it, run <code>strings</code> over the compiled Dart code, or put a proxy like mitmproxy between the phone and the internet and read the <code>Authorization</code> header as it goes past. A long string that starts with <code>sk-</code> is not hard to spot.</p>
<p>The usual "fixes" don't change this:</p>
<ul>
<li><strong><code>.env</code> files with <code>flutter_dotenv</code></strong>. The <code>.env</code> file is bundled as an asset. It's sitting in the app package as plain text.</li>
<li><strong><code>--dart-define</code> or <code>--dart-define-from-file</code></strong>. These keep the key out of your Git repo, which is good, but the value is compiled into the app. It's still in the binary.</li>
<li><strong>Obfuscation</strong>. Flutter's own docs say obfuscation "only renames symbols" and does not protect against reverse engineering, and that storing secrets in an app is "a poor security practice" (<a href="https://docs.flutter.dev/deployment/obfuscate">Flutter docs</a>).</li>
<li><strong>Splitting or encrypting the key</strong>. The app has to rebuild the real key to use it, so the code to rebuild it ships too. And once the key is in memory, it shows up in the network request anyway.</li>
</ul>
<p>So the rule is simple: if a request carries your provider key, that request must come from a server, not from the phone.</p>
<h2>The backend proxy pattern</h2>
<p>The app never talks to OpenAI or Gemini directly. It talks to your endpoint:</p>
<pre><code>Flutter app  --(user's auth token)--&gt;  your /chat endpoint  --(API key)--&gt;  LLM provider
             &lt;--(streamed text)-------                      &lt;--(SSE)-------
</code></pre>
<p>Your endpoint can be a tiny Dart server on Cloud Run or a VPS, a Firebase Cloud Function, a Supabase Edge Function, or anything else that can hold an environment variable and make an HTTPS request. It does five jobs:</p>
<ol>
<li><strong>Holds the key</strong> in an environment variable or secret manager. It never leaves the server.</li>
<li><strong>Checks who is calling.</strong> The app sends the user's auth token (a Firebase ID token, a Supabase JWT, your own session token). No valid user, no AI call.</li>
<li><strong>Limits each user.</strong> A per-user rate limit and, ideally, a daily or monthly quota.</li>
<li><strong>Decides the request.</strong> Model, system prompt and maximum reply length are set on the server. The app only sends the conversation.</li>
<li><strong>Streams the reply back</strong> so the UI can show text as it arrives.</li>
</ol>
<p>Point 4 is easy to undervalue. If the model name is hard-coded in your app, changing it means a store release and waiting for users to update. If it's an environment variable on the server, you can switch from one OpenAI model to a cheaper one, or to Gemini, in a minute. Google even offers an OpenAI-compatible endpoint for Gemini at <code>https://generativelanguage.googleapis.com/v1beta/openai/</code> (<a href="https://aistudio.google.com/docs/openai">Gemini docs</a>), so the same proxy code can talk to either provider by changing the base URL, key and model name.</p>
<blockquote>
<p><strong>How I do it in my own apps:</strong> none of my AI apps ship an API key. Evoke AI and Hashtag AI Expert call my own backend on a Contabo server, and Inlinker, a client company's app, runs its backend on DigitalOcean. The apps only talk to that backend, and the backend holds the keys and calls the AI providers. Keys never go into the app code or a GitHub repository. Around that I use Firebase and Supabase for app data and auth, Firebase Cloud Messaging for notifications, and Crashlytics to catch crashes in the live apps.</p>
</blockquote>
<h2>A minimal Dart proxy</h2>
<p>Here is a complete proxy using only <code>dart:io</code> and <code>package:http</code>. It speaks the OpenAI Chat Completions format: <code>POST {base}/chat/completions</code> with <code>model</code>, <code>messages</code> and <code>"stream": true</code>, and a server-sent events (SSE) stream back where each <code>data:</code> line holds a chunk with the new text in <code>choices[0].delta.content</code>, ending with <code>data: [DONE]</code> (<a href="https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create">OpenAI API reference</a>).</p>
<pre><code class="language-dart">import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:http/http.dart' as http;

// Everything provider-specific lives here, on the server.
final apiKey = Platform.environment['LLM_API_KEY'] ?? '';
final baseUrl =
    Platform.environment['LLM_BASE_URL'] ?? 'https://api.openai.com/v1';
final model = Platform.environment['LLM_MODEL'] ?? '';
const systemPrompt =
    'You are a helpful assistant inside a mobile app. '
    'Keep answers short.';

// Simple per-user limit: 20 requests per 10 minutes.
const maxRequests = 20;
const window = Duration(minutes: 10);
final _hits = &lt;String, List&lt;DateTime&gt;&gt;{};

final _upstream = http.Client();

Future&lt;void&gt; main() async {
  if (apiKey.isEmpty || model.isEmpty) {
    stderr.writeln('Set LLM_API_KEY and LLM_MODEL.');
    exit(1);
  }
  final port = int.parse(Platform.environment['PORT'] ?? '8080');
  final server = await HttpServer.bind(InternetAddress.anyIPv4, port);
  print('Proxy listening on port ${server.port}');
  await for (final request in server) {
    unawaited(_handle(request));
  }
}

Future&lt;void&gt; _handle(HttpRequest req) async {
  final res = req.response;
  try {
    if (req.method != 'POST' || req.uri.path != '/chat') {
      return _fail(res, HttpStatus.notFound, 'not found');
    }

    // 1. Who is calling? Never trust a user id sent in the body.
    final auth = req.headers.value(HttpHeaders.authorizationHeader) ?? '';
    final userId = auth.startsWith('Bearer ')
        ? await verifyToken(auth.substring(7))
        : null;
    if (userId == null) {
      return _fail(res, HttpStatus.unauthorized, 'sign in first');
    }

    // 2. Per-user rate limit.
    if (!_allow(userId)) {
      res.headers.set('Retry-After', '60');
      return _fail(res, HttpStatus.tooManyRequests, 'slow down');
    }

    // 3. Validate input: only user/assistant turns, capped size.
    final body = jsonDecode(await utf8.decodeStream(req)) as Map;
    final history = (body['messages'] as List)
        .cast&lt;Map&gt;()
        .where((m) =&gt; m['role'] == 'user' || m['role'] == 'assistant')
        .map((m) =&gt; {'role': m['role'], 'content': '${m['content']}'})
        .toList();
    final recent = history.length &gt; 20
        ? history.sublist(history.length - 20)
        : history;
    if (recent.isEmpty || recent.any((m) =&gt; m['content']!.length &gt; 4000)) {
      return _fail(res, HttpStatus.badRequest, 'bad messages');
    }

    // 4. Forward to the provider. Model, system prompt and token cap
    //    are chosen here, not in the app.
    final upstreamReq =
        http.Request('POST', Uri.parse('$baseUrl/chat/completions'))
          ..headers['Authorization'] = 'Bearer $apiKey'
          ..headers['Content-Type'] = 'application/json'
          ..body = jsonEncode({
            'model': model,
            'stream': true,
            'max_completion_tokens': 500,
            'safety_identifier': userId, // OpenAI field; check your provider
            'messages': [
              {'role': 'system', 'content': systemPrompt},
              ...recent,
            ],
          });
    final upstream = await _upstream.send(upstreamReq);
    if (upstream.statusCode != 200) {
      stderr.writeln(
        'upstream ${upstream.statusCode}: '
        '${await upstream.stream.bytesToString()}',
      );
      return _fail(res, HttpStatus.badGateway, 'AI service unavailable');
    }

    // 5. Read the provider's SSE stream and send plain text deltas on.
    res.headers.contentType = ContentType('text', 'plain', charset: 'utf-8');
    res.bufferOutput = false;
    final lines = upstream.stream
        .transform(utf8.decoder)
        .transform(const LineSplitter());
    await for (final line in lines) {
      if (!line.startsWith('data: ')) continue;
      final data = line.substring(6);
      if (data == '[DONE]') break;
      final chunk = jsonDecode(data) as Map&lt;String, dynamic&gt;;
      final choices = chunk['choices'] as List;
      if (choices.isEmpty) continue;
      final text = choices[0]['delta']?['content'];
      if (text is String &amp;&amp; text.isNotEmpty) {
        res.write(text);
        await res.flush();
      }
    }
    await res.close();
  } catch (e) {
    stderr.writeln('error: $e');
    try {
      await _fail(res, HttpStatus.internalServerError, 'server error');
    } catch (_) {
      // Headers already sent; the client sees a cut-off stream.
      await res.close();
    }
  }
}

/// Placeholder. In a real app, verify a Firebase ID token, Supabase JWT
/// or your own session token here and return the user's id.
Future&lt;String?&gt; verifyToken(String token) async {
  const demoUsers = {'demo-token-alice': 'alice', 'demo-token-bob': 'bob'};
  return demoUsers[token];
}

bool _allow(String userId) {
  final now = DateTime.now();
  final hits = _hits.putIfAbsent(userId, () =&gt; [])
    ..removeWhere((t) =&gt; now.difference(t) &gt; window);
  if (hits.length &gt;= maxRequests) return false;
  hits.add(now);
  return true;
}

Future&lt;void&gt; _fail(HttpResponse res, int status, String message) async {
  res.statusCode = status;
  res.headers.contentType = ContentType.json;
  res.write(jsonEncode({'error': message}));
  await res.close();
}
</code></pre>
<p>Run it with the key in the environment, never in a file you commit:</p>
<pre><code class="language-bash">LLM_API_KEY=... LLM_MODEL=your-model-name dart run bin/proxy.dart
</code></pre>
<p>A few choices in there are deliberate:</p>
<ul>
<li><strong>The app can't send a system message.</strong> The server drops any role other than <code>user</code> and <code>assistant</code> and adds its own system prompt. Otherwise anyone can turn your "recipe helper" into a free general-purpose chatbot.</li>
<li><strong>History and message size are capped.</strong> Chat APIs bill for input tokens too, and the whole conversation is sent on every turn. Sending only the last 20 turns and refusing huge messages keeps each request's cost bounded.</li>
<li><strong>The reply length is capped</strong> with <code>max_completion_tokens</code>. OpenAI now uses this name; the older <code>max_tokens</code> is deprecated. Parameter names differ between providers and their OpenAI-compatible layers, so check the docs for the one you use.</li>
<li><strong>The proxy turns SSE into plain text.</strong> The app receives raw text chunks, not the provider's event format. If you later switch to a provider with a different streaming format, only the server changes.</li>
<li><strong>Provider errors stay on the server.</strong> The app gets a generic 502, and the real error goes to your logs.</li>
</ul>
<p>The in-memory rate limiter is fine for a single server instance and for learning. With more than one instance, or serverless functions that start fresh, the counter has to live somewhere shared: Redis, Firestore, or a database row per user per day. For <code>verifyToken</code>, use the official verification for your auth system, for example the Firebase Admin SDK's ID token check, or verifying a Supabase JWT with your project's key.</p>
<h2>The client: consuming the stream in Dart</h2>
<p>This function is plain Dart with <code>package:http</code>, so it runs unchanged in a Flutter app:</p>
<pre><code class="language-dart">import 'dart:convert';

import 'package:http/http.dart' as http;

class ChatException implements Exception {
  ChatException(this.statusCode, this.message);
  final int statusCode;
  final String message;
  @override
  String toString() =&gt; 'ChatException($statusCode): $message';
}

/// Sends the conversation to your backend and yields the reply as it
/// streams in. The app never sees a provider API key.
Stream&lt;String&gt; streamChat({
  required http.Client client,
  required Uri endpoint,
  required String userToken,
  required List&lt;Map&lt;String, String&gt;&gt; messages,
}) async* {
  final request = http.Request('POST', endpoint)
    ..headers['Authorization'] = 'Bearer $userToken'
    ..headers['Content-Type'] = 'application/json'
    ..body = jsonEncode({'messages': messages});

  final response = await client.send(request);
  if (response.statusCode != 200) {
    final body = await response.stream.bytesToString();
    throw ChatException(response.statusCode, body);
  }
  yield* response.stream.transform(utf8.decoder);
}
</code></pre>
<p>The important part is <code>client.send</code> instead of <code>http.post</code>. <code>http.post</code> waits for the whole body. <code>send</code> gives you a <code>StreamedResponse</code>, and you get the bytes as they arrive. <code>utf8.decoder</code> as a stream transformer also handles a multi-byte character (an emoji, an Urdu letter, an accented "é") that is split across two network chunks.</p>
<h3>How I tested it</h3>
<p>I ran both pieces against a fake upstream server that checks the API key header, records the request, and sends back an OpenAI-style SSE stream in 7-byte pieces, so that both SSE lines and UTF-8 characters get split mid-way. The proxy ran as a separate process with a dummy key in its environment. The checks that passed:</p>
<ul>
<li>The full reply arrived, correctly decoded, in more than one chunk.</li>
<li>The upstream request had the server's model, <code>"stream": true</code>, and only <code>system,user</code> roles (the client's injected system message was dropped).</li>
<li>The user id sent upstream came from the token, not the request body.</li>
<li>A made-up token got <code>401</code>.</li>
<li>One user got 20 replies, then <code>429</code>. A second user was not affected.</li>
</ul>
<p><code>dart analyze</code> reported no issues. No real API key was used and nothing was sent to OpenAI.</p>
<h2>The chat UI state in Flutter</h2>
<p>The UI needs a list of messages, a flag for "a reply is streaming", and a way to grow the last assistant message as chunks arrive. A <code>ChangeNotifier</code> is enough. This code is illustrative: I haven't compiled it here, but it uses only standard Flutter APIs and the <code>streamChat</code> function above.</p>
<pre><code class="language-dart">class ChatController extends ChangeNotifier {
  ChatController(this._client, this._endpoint, this._token);
  final http.Client _client;
  final Uri _endpoint;
  final Future&lt;String&gt; Function() _token; // e.g. user.getIdToken()

  final messages = &lt;Map&lt;String, String&gt;&gt;[];
  bool streaming = false;
  String? error;

  Future&lt;void&gt; send(String text) async {
    if (streaming || text.trim().isEmpty) return;
    messages.add({'role': 'user', 'content': text.trim()});
    messages.add({'role': 'assistant', 'content': ''});
    streaming = true;
    error = null;
    notifyListeners();

    try {
      final history = messages.sublist(0, messages.length - 1);
      await for (final piece in streamChat(
        client: _client,
        endpoint: _endpoint,
        userToken: await _token(),
        messages: history,
      )) {
        messages.last['content'] = messages.last['content']! + piece;
        notifyListeners();
      }
    } on ChatException catch (e) {
      messages.removeLast();
      error = e.statusCode == 429
          ? 'You are sending messages too fast. Try again in a minute.'
          : 'Could not get a reply. Please try again.';
    } finally {
      streaming = false;
      notifyListeners();
    }
  }
}
</code></pre>
<p>In the widget, wrap a <code>ListView.builder</code> in a <code>ListenableBuilder(listenable: controller, ...)</code>, disable the send button while <code>controller.streaming</code> is true, and show <code>controller.error</code> in a <code>SnackBar</code> or under the input field. If you already use Riverpod or Bloc, the same state fits in a notifier or cubit. Two small things that matter in practice: scroll to the bottom as text grows, and handle a 429 with a clear message instead of a generic error, because a user who hits the limit should know why.</p>
<h2>Costs and abuse: limits worth setting</h2>
<p>Your proxy is now a public endpoint that spends money. Treat it that way:</p>
<ul>
<li><strong>Require sign-in for AI features.</strong> Anonymous access makes per-user limits meaningless, because a new "user" costs nothing.</li>
<li><strong>Rate limit per user</strong> (requests per minute) to stop scripts, and <strong>quota per user</strong> (messages or tokens per day or month) to cap what one account can cost you. Tie the quota to the plan: free users get a small daily number, paying users more.</li>
<li><strong>Cap tokens on every request</strong>: input (history length, message size) and output (<code>max_completion_tokens</code>).</li>
<li><strong>Set a budget alert and a hard spending limit</strong> in your provider's billing settings. This is your last line of defence if everything else fails.</li>
<li><strong>Log usage per user.</strong> The streaming response can include token usage at the end if you ask for it (<code>stream_options: {"include_usage": true}</code> in OpenAI's API). Store it so you can see who costs what.</li>
<li><strong>Pick the model on purpose.</strong> A smaller model is often good enough for chat inside an app, and costs a fraction of the largest one. Because the model is a server setting, you can test this without a release.</li>
<li><strong>Add App Check or Play Integrity / App Attest</strong> if you want to block requests that don't come from your real app. It raises the bar for scripts that copy a user's token.</li>
</ul>
<blockquote>
<p><strong>What I did in <a href="https://neemii.dev/work/evoke-ai/">Evoke AI</a>:</strong> every new account gets a small free quota of 5 AI prompts. After that, users either buy credits or watch an ad for each prompt. The backend enforces the quota, not the app, so a modified app can't skip it. Because every prompt is either paid for or covered by an ad, AI costs grow with revenue instead of with free usage.</p>
</blockquote>
<h2>The managed alternative: Firebase AI Logic</h2>
<p>If you'd rather not run a server, Firebase AI Logic (the <code>firebase_ai</code> Flutter package, formerly Vertex AI in Firebase) lets the app call Gemini models through Firebase, without a Gemini API key in the app. Firebase acts as the gateway, and Firebase App Check verifies that requests come from your genuine app before they're forwarded (<a href="https://firebase.google.com/docs/ai-logic/app-check">App Check for Firebase AI Logic</a>). Firebase's docs say App Check enforcement is required starting November 2, 2026, and support limited-use tokens with replay protection for tighter security. There is also a per-user rate limit, 100 requests per minute per user by default (<a href="https://firebase.google.com/docs/ai-logic/quotas">Firebase AI Logic quotas</a>).</p>
<p>The trade-offs, honestly:</p>
<ul>
<li><strong>Good</strong>: no server to deploy, real attestation of the app, official Flutter SDK with streaming.</li>
<li><strong>Less good</strong>: you're tied to Google's models through this route, the system prompt and model name usually live in app code (Firebase Remote Config helps here), and the built-in per-user limit is one value for all users. Per-plan quotas, like "free users get 10 messages a day", still need your own logic.</li>
</ul>
<p>For a prototype or an app that only needs Gemini, Firebase AI Logic is a sensible choice. For multiple providers, paid plans with quotas, or a system prompt you want to keep off the device, a small proxy gives you more control.</p>
<h2>Summary</h2>
<ul>
<li>An API key in a Flutter app is public. <code>.env</code>, <code>--dart-define</code> and obfuscation don't change that.</li>
<li>Put the key on a server. The app sends the user's auth token and the conversation, nothing else.</li>
<li>Choose the model, system prompt and token limits on the server, so you can change them without a release.</li>
<li>Stream the reply with <code>client.send</code> and <code>utf8.decoder</code>, and grow the last message in your chat state.</li>
<li>Rate limit per user, set daily quotas, cap tokens, and set a billing alert.</li>
</ul>
<p>If you're planning an AI feature for your app and want it built this way from the start, see my <a href="https://neemii.dev/services/ai-app-development/">AI app development service</a>. I'm Muhammad Naeem, a Flutter developer in Lahore, and I've shipped AI apps that use OpenAI, Gemini and Claude. <a href="https://neemii.dev/#contact">Tell me about your app</a> and I'll reply with how I'd set it up and what it would cost.</p>
<hr />
<p><em>Originally published at <a href="https://neemii.dev/blog/flutter-ai-chat-without-exposing-api-key/">neemii.dev</a>. I'm Muhammad Naeem, a Flutter developer with 10+ apps on the App Store and Google Play. More free tools for Flutter developers: <a href="https://neemii.dev/tools/">neemii.dev/tools</a>.</em></p>
]]></content:encoded></item><item><title><![CDATA[Flutter JSON Parsing: fromJson, Null Safety and Code Generation]]></title><description><![CDATA[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…]]></description><link>https://neemii.hashnode.dev/flutter-json-parsing-fromjson-null-safety-and-code-generation-mwor9smx</link><guid isPermaLink="true">https://neemii.hashnode.dev/flutter-json-parsing-fromjson-null-safety-and-code-generation-mwor9smx</guid><category><![CDATA[Flutter]]></category><category><![CDATA[Dart]]></category><category><![CDATA[json]]></category><category><![CDATA[mobile]]></category><dc:creator><![CDATA[Muhammad Naeem]]></dc:creator><pubDate>Fri, 20 Nov 2026 09:07:19 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6afe88d80a8396bd81928ac1/af8f9879-461e-4492-8d92-7d7fedcc579f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>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.</p>
<p>This post covers both, in the order you'll meet them: <code>jsonDecode</code>, a hand-written model, the null safety traps, nested objects and lists, <code>json_serializable</code>, <code>freezed</code>, and the error messages that show up when something doesn't match.</p>
<h2>Step 1: jsonDecode gives you dynamic data</h2>
<p><code>jsonDecode</code> from <code>dart:convert</code> turns a JSON string into plain Dart values: <code>Map&lt;String, dynamic&gt;</code> for objects, <code>List&lt;dynamic&gt;</code> for arrays, and <code>String</code>, <code>int</code>, <code>double</code>, <code>bool</code> or <code>null</code> for the rest.</p>
<pre><code class="language-dart">import 'dart:convert';

void main() {
  const body = '{"id": 7, "name": "Ayesha", "email": null}';
  final data = jsonDecode(body) as Map&lt;String, dynamic&gt;;
  print(data['name']); // Ayesha
  print(data['id'].runtimeType); // int
}
</code></pre>
<p>You could pass <code>data</code> around your app and read <code>data['name']</code> everywhere. Don't. Every read is untyped, a typo in a key returns <code>null</code> instead of a compile error, and when the API changes you find out from a crash report. Convert it to a class once, at the edge of your app.</p>
<h2>Step 2: a model class with fromJson and toJson</h2>
<p>The standard pattern is a <code>fromJson</code> factory constructor and a <code>toJson</code> method:</p>
<pre><code class="language-dart">class User {
  const User({required this.id, required this.name, this.email});

  final int id;
  final String name;
  final String? email;

  factory User.fromJson(Map&lt;String, dynamic&gt; json) =&gt; User(
        id: json['id'] as int,
        name: json['name'] as String,
        email: json['email'] as String?,
      );

  Map&lt;String, dynamic&gt; toJson() =&gt; {
        'id': id,
        'name': name,
        'email': email,
      };
}
</code></pre>
<p>Usage:</p>
<pre><code class="language-dart">final user = User.fromJson(data);
print(user.email); // null
print(jsonEncode(user.toJson())); // {"id":7,"name":"Ayesha","email":null}
</code></pre>
<p>The <code>as</code> casts are the important part. They are where the type check happens, and they are where your app will throw if the API sends something you didn't expect. That is a good thing: it fails at the parsing line, with a clear message, instead of three screens later.</p>
<p>If you don't want to type these classes by hand, paste a real response into my <a href="https://neemii.dev/tools/json-to-dart/">JSON to Dart converter</a>. It produces this same style of model (plain Dart, <code>json_serializable</code> or <code>freezed</code>), runs in your browser, and doesn't send your JSON anywhere.</p>
<h2>Null safety: where most parsing bugs come from</h2>
<p>Dart's null safety only protects you after the data is inside a typed field. The cast from <code>dynamic</code> is where you decide what's allowed to be null, and getting that decision wrong is the most common source of crashes.</p>
<h3>int vs double</h3>
<p>JSON has one number type. Dart has two. <code>jsonDecode('450')</code> gives you an <code>int</code>, and <code>jsonDecode('450.0')</code> gives you a <code>double</code>. Many APIs send prices as <code>450</code> one day and <code>450.5</code> the next, so this will eventually crash on a phone:</p>
<pre><code class="language-dart">price: json['price'] as double, // throws when the API sends 450
</code></pre>
<p>Read every <code>double</code> through <code>num</code> instead:</p>
<pre><code class="language-dart">price: (json['price'] as num).toDouble(),
</code></pre>
<p>One detail that makes this bug sneaky: on Flutter web compiled to JavaScript (the default build), <code>int</code> and <code>double</code> are both JavaScript numbers, so <code>450 as double</code> succeeds. The same line compiled with <code>dart compile js</code> printed <code>450</code>, while the Dart VM threw. If you test mainly on web, you can ship this bug to Android and iOS without seeing it once.</p>
<h3>Missing keys and null values</h3>
<p>Reading a key that isn't in the map returns <code>null</code>, the same as a key whose value is <code>null</code>. So <code>json['email'] as String?</code> handles both cases. A field that's required in your class but missing from the response throws:</p>
<pre><code class="language-text">type 'Null' is not a subtype of type 'String' in type cast
</code></pre>
<p>For each field, decide which of three things it is:</p>
<ol>
<li><strong>Always present</strong>: non-nullable type, plain cast (<code>as String</code>).</li>
<li><strong>Sometimes missing, and null means something</strong>: nullable type (<code>String?</code>, <code>as String?</code>).</li>
<li><strong>Sometimes missing, but there's a sensible default</strong>: nullable cast plus <code>??</code>.</li>
</ol>
<pre><code class="language-dart">status: json['status'] as String? ?? 'pending',
</code></pre>
<p>Don't make everything nullable just to stop crashes. You'll trade one crash at parse time for <code>!</code> operators and null checks spread through your UI code. Be strict where the API contract is strict, and loose only where it really is optional.</p>
<blockquote>
<p><strong>From my own work:</strong> on a government survey app I'm working on (I can't share details), records were getting stuck on some enumerators' devices and never reached the server. I went through the Postman responses, the Grafana logs and the field notes, and found the cause: in a few scenarios a record was missing an ID in the local database, so the JSON the app sent was not what the server expected, and the server rejected it every time the app retried. Making the parser more lenient would only have hidden the problem. Instead I added an auto-repair step that restores any missing survey ID in the local database before upload, so the server accepts the JSON and the stuck records go through. The lesson: when JSON fails, check the data you're serialising, not just the parsing code.</p>
</blockquote>
<h3>When the API sends the wrong type</h3>
<p>Some backends send <code>"id": "42"</code> in one endpoint and <code>"id": 42</code> in another. If you can't get the backend fixed, read it with a small helper instead of a cast:</p>
<pre><code class="language-dart">int readInt(Object? v) =&gt; switch (v) {
      int i =&gt; i,
      num n =&gt; n.toInt(),
      String s =&gt; int.parse(s),
      _ =&gt; throw FormatException('Expected an int, got $v'),
    };
</code></pre>
<p>Keep these helpers few and deliberate. Each one hides a backend inconsistency that someone should eventually fix.</p>
<h2>Nested objects and lists</h2>
<p>Real responses are nested. Here's an order with a customer object, a list of items and a list of strings:</p>
<pre><code class="language-json">{
  "id": 1042,
  "total": 450,
  "customer": {"name": "Sara", "phone": null},
  "items": [
    {"title": "Chai", "qty": 2, "price": 150},
    {"title": "Samosa", "qty": 3, "price": 50.0}
  ],
  "tags": ["express", "paid"]
}
</code></pre>
<p>Each nested object gets its own class with its own <code>fromJson</code>. Lists are decoded as <code>List&lt;dynamic&gt;</code>, so you map each element:</p>
<pre><code class="language-dart">factory Order.fromJson(Map&lt;String, dynamic&gt; json) =&gt; Order(
      id: json['id'] as int,
      status: json['status'] as String? ?? 'pending',
      total: (json['total'] as num).toDouble(),
      customer: Customer.fromJson(json['customer'] as Map&lt;String, dynamic&gt;),
      items: (json['items'] as List&lt;dynamic&gt;)
          .map((e) =&gt; OrderItem.fromJson(e as Map&lt;String, dynamic&gt;))
          .toList(),
      tags: (json['tags'] as List&lt;dynamic&gt;? ?? const [])
          .map((e) =&gt; e as String)
          .toList(),
      coupon: json['coupon'] as String?,
    );

Map&lt;String, dynamic&gt; toJson() =&gt; {
      'id': id,
      'status': status,
      'total': total,
      'customer': customer.toJson(),
      'items': items.map((e) =&gt; e.toJson()).toList(),
      'tags': tags,
      'coupon': coupon,
    };
</code></pre>
<p><code>Customer</code> and <code>OrderItem</code> follow the same pattern as <code>User</code> above, with <code>OrderItem.price</code> read as <code>(json['price'] as num).toDouble()</code>. Note that <code>toJson</code> calls <code>toJson()</code> on the nested objects too, so you get plain maps all the way down.</p>
<h3>When the top level is a list</h3>
<p>If the endpoint returns an array, cast the decoded value to <code>List&lt;dynamic&gt;</code>:</p>
<pre><code class="language-dart">final users = (jsonDecode(body) as List&lt;dynamic&gt;)
    .map((e) =&gt; User.fromJson(e as Map&lt;String, dynamic&gt;))
    .toList();
</code></pre>
<p>Many APIs wrap the list instead: <code>{"data": [...], "page": 1}</code>. Then you cast to a map first and read the list from it:</p>
<pre><code class="language-dart">final map = jsonDecode(body) as Map&lt;String, dynamic&gt;;
final users = (map['data'] as List&lt;dynamic&gt;)
    .map((e) =&gt; User.fromJson(e as Map&lt;String, dynamic&gt;))
    .toList();
</code></pre>
<h3>Large responses</h3>
<p>Decoding a big response on the main isolate can drop frames. Move the parsing to another isolate with <code>Isolate.run</code> (or Flutter's <code>compute</code>):</p>
<pre><code class="language-dart">List&lt;User&gt; parseUsers(String body) =&gt; (jsonDecode(body) as List&lt;dynamic&gt;)
    .map((e) =&gt; User.fromJson(e as Map&lt;String, dynamic&gt;))
    .toList();

final users = await Isolate.run(() =&gt; parseUsers(body));
</code></pre>
<p>The closure and what it captures (here, the <code>body</code> string) are copied into the new isolate, so keep it small and self-contained. Only do this when you've seen jank on a real device; for small payloads it adds overhead without any benefit.</p>
<h2>json_serializable: let the generator write fromJson</h2>
<p>Writing models by hand is fine for a few classes. Past that, the casts get repetitive and a renamed field is easy to miss in <code>toJson</code>. <code>json_serializable</code> generates both methods from annotations.</p>
<p>Add the packages:</p>
<pre><code class="language-text">flutter pub add json_annotation dev:build_runner dev:json_serializable
</code></pre>
<p>Then annotate the model and point it at the file that will be generated:</p>
<pre><code class="language-dart">import 'package:json_annotation/json_annotation.dart';

part 'product.g.dart';

@JsonSerializable(explicitToJson: true)
class Product {
  const Product({
    required this.id,
    required this.title,
    required this.price,
    this.imageUrl,
    this.inStock = true,
    required this.variants,
  });

  final int id;
  final String title;
  final double price;

  @JsonKey(name: 'image_url')
  final String? imageUrl;

  @JsonKey(name: 'in_stock')
  final bool inStock;

  final List&lt;Variant&gt; variants;

  factory Product.fromJson(Map&lt;String, dynamic&gt; json) =&gt;
      _$ProductFromJson(json);

  Map&lt;String, dynamic&gt; toJson() =&gt; _$ProductToJson(this);
}
</code></pre>
<p><code>Variant</code> is another <code>@JsonSerializable()</code> class with the same two one-line methods. Generate the code:</p>
<pre><code class="language-text">dart run build_runner build --delete-conflicting-outputs
</code></pre>
<p>Use <code>watch</code> instead of <code>build</code> to regenerate on every save. The generated <code>product.g.dart</code> reads numbers safely for you:</p>
<pre><code class="language-dart">Product _$ProductFromJson(Map&lt;String, dynamic&gt; json) =&gt; Product(
  id: (json['id'] as num).toInt(),
  title: json['title'] as String,
  price: (json['price'] as num).toDouble(),
  imageUrl: json['image_url'] as String?,
  inStock: json['in_stock'] as bool? ?? true,
  variants: (json['variants'] as List&lt;dynamic&gt;)
      .map((e) =&gt; Variant.fromJson(e as Map&lt;String, dynamic&gt;))
      .toList(),
);
</code></pre>
<p>Things worth knowing:</p>
<ul>
<li><strong><code>explicitToJson: true</code></strong> matters for nested objects. Without it, <code>toJson()</code> puts the <code>Variant</code> objects themselves in the map, not maps. <code>jsonEncode</code> still works because it calls <code>toJson()</code> on them, but anything else that expects a plain map (a local database, a test comparing maps) will not.</li>
<li><strong>Default values</strong> in the constructor (<code>this.inStock = true</code>) are used when the key is missing or null.</li>
<li><strong>Project-wide settings</strong> go in <code>build.yaml</code> at the project root, so you don't repeat them on every class:</li>
</ul>
<pre><code class="language-yaml">targets:
  $default:
    builders:
      json_serializable:
        options:
          explicit_to_json: true
          field_rename: snake
</code></pre>
<p>With <code>field_rename: snake</code>, a Dart field <code>fullName</code> maps to the JSON key <code>full_name</code> without a <code>@JsonKey</code> on every field.</p>
<p>The cost is the build step: a <code>part</code> directive in every model, generated files in your repo (or a build step in CI), and a few seconds of waiting after each model change.</p>
<h2>freezed: when you want more than JSON</h2>
<p><code>freezed</code> is a different kind of tool. It generates immutable data classes: <code>copyWith</code>, <code>==</code> and <code>hashCode</code> based on values, <code>toString</code>, and sealed unions. For JSON it hands off to <code>json_serializable</code>, so you install both.</p>
<pre><code class="language-dart">import 'package:freezed_annotation/freezed_annotation.dart';

part 'product.freezed.dart';
part 'product.g.dart';

@freezed
abstract class Product with _$Product {
  const factory Product({
    required int id,
    required String title,
    required double price,
    @JsonKey(name: 'image_url') String? imageUrl,
    @JsonKey(name: 'in_stock') @Default(true) bool inStock,
  }) = _Product;

  factory Product.fromJson(Map&lt;String, dynamic&gt; json) =&gt;
      _$ProductFromJson(json);
}
</code></pre>
<p>With that you get <code>product.copyWith(price: 1999)</code> and <code>a == b</code> comparing values, which is what state management (Bloc, Riverpod) wants when it decides whether to rebuild.</p>
<p>Two notes for current versions (freezed 3.x). The class must be declared <code>abstract</code> (or <code>sealed</code> for unions), which older tutorials don't show. And <code>@JsonKey</code> on constructor parameters triggers the analyzer warning <code>invalid_annotation_target</code>; freezed's own docs recommend turning it off in <code>analysis_options.yaml</code>:</p>
<pre><code class="language-yaml">analyzer:
  errors:
    invalid_annotation_target: ignore
</code></pre>
<p>Is it worth it? If you only need to parse API responses and show them, no: <code>json_serializable</code> alone is less generated code and fewer concepts. <code>freezed</code> earns its place when your models are also your app state, when you update them with <code>copyWith</code> a lot, or when you want sealed classes like <code>Loading | Loaded | Error</code> with exhaustive <code>switch</code>.</p>
<h2>Which approach for which app</h2>
<table>
<thead>
<tr>
<th>Situation</th>
<th>Approach</th>
</tr>
</thead>
<tbody><tr>
<td>Prototype, small app, a handful of models</td>
<td>Hand-written models (or generated once with the <a href="https://neemii.dev/tools/json-to-dart/">converter</a>)</td>
</tr>
<tr>
<td>Many models, a team, an API that keeps changing</td>
<td><code>json_serializable</code></td>
</tr>
<tr>
<td>Models are also app state; you need <code>copyWith</code>, equality, unions</td>
<td><code>freezed</code> + <code>json_serializable</code></td>
</tr>
</tbody></table>
<p>You can mix them. Starting with hand-written models and moving to <code>json_serializable</code> later is a mechanical change, because the public API (<code>fromJson</code> and <code>toJson</code>) stays the same. Code generation is still the standard way to do this in Dart: the macros experiment that promised <code>@JsonCodable</code> without <code>build_runner</code> was stopped by the Dart team in early 2025.</p>
<blockquote>
<p><strong>What I use:</strong> in my own client apps I write plain <code>fromJson</code>/<code>toJson</code> by hand. It keeps the models readable and adds no code generation step to the build. I then check each model against the official Flutter and Dart documentation, and use AI tools as a second reviewer to catch a missed null case or wrong cast.</p>
</blockquote>
<h2>Common errors and what they mean</h2>
<p>These are the exact messages from the Dart VM (which is what runs your app on Android and iOS), reproduced with the code next to each one.</p>
<p><strong><code>type 'int' is not a subtype of type 'double' in type cast</code></strong>
You cast a whole number to <code>double</code>: <code>json['price'] as double</code> with <code>"price": 450</code>. Fix: <code>(json['price'] as num).toDouble()</code>. Without the <code>as</code> (for example <code>final double price = json['price'];</code>) the message is the same minus "in type cast".</p>
<p><strong><code>type 'Null' is not a subtype of type 'String' in type cast</code></strong>
A field you declared non-nullable was <code>null</code> or missing. Check the raw response. Either make the field nullable, give it a default with <code>??</code>, or fix the backend.</p>
<p><strong><code>type 'List&lt;dynamic&gt;' is not a subtype of type 'List&lt;String&gt;' in type cast</code></strong>
<code>json['tags'] as List&lt;String&gt;</code>. A decoded JSON list is always <code>List&lt;dynamic&gt;</code>, even if every element is a string. Fix: <code>(json['tags'] as List&lt;dynamic&gt;).map((e) =&gt; e as String).toList()</code>.</p>
<p><strong><code>type '_Map&lt;String, dynamic&gt;' is not a subtype of type 'List&lt;dynamic&gt;' in type cast</code></strong>
You expected an array at the top level, but the API wraps it: <code>{"data": [...]}</code>. Cast to <code>Map&lt;String, dynamic&gt;</code> first and read the list from <code>map['data']</code>. <code>_Map</code> is just the private class <code>jsonDecode</code> uses for objects.</p>
<p><strong><code>type '_Map&lt;String, dynamic&gt;' is not a subtype of type 'Map&lt;String, String&gt;' in type cast</code></strong>
Same root cause as the list case: decoded maps are always <code>Map&lt;String, dynamic&gt;</code>. Cast to that and convert the values, or better, write a class for the nested object.</p>
<p><strong><code>type 'String' is not a subtype of type 'int' in type cast</code></strong>
The API sent <code>"id": "42"</code>. Fix the backend if you can; otherwise use a helper like <code>readInt</code> above.</p>
<p><strong><code>type 'String' is not a subtype of type 'int' of 'index'</code></strong>
You indexed a list with a string key: <code>list['id']</code> where <code>list</code> is the decoded array. Take an element first (<code>list[0]['id']</code>), or map the list into models.</p>
<p><strong><code>FormatException: Unexpected character (at character 1)</code></strong>
The body isn't JSON at all. Most often it's an HTML error page from a proxy, a login redirect, or a 500. Check the status code before calling <code>jsonDecode</code>. An empty body gives <code>FormatException: Unexpected end of input (at character 1)</code>.</p>
<h2>Summary</h2>
<ul>
<li>Decode once with <code>jsonDecode</code>, convert to typed models right away, and keep <code>dynamic</code> out of your widgets.</li>
<li>Read doubles through <code>num</code>. Decide per field what's required, optional or defaulted.</li>
<li>Map lists element by element; cast nested objects to <code>Map&lt;String, dynamic&gt;</code>.</li>
<li>Move to <code>json_serializable</code> when the models multiply, and add <code>freezed</code> when they become app state.</li>
</ul>
<p>If you want the boilerplate done for you, paste your API response into the free <a href="https://neemii.dev/tools/json-to-dart/">JSON to Dart model converter</a>. It handles nullable fields, int/double, ISO dates as <code>DateTime</code>, snake_case keys and nested lists, and outputs plain Dart, <code>json_serializable</code> or <code>freezed</code>. And if you're building a Flutter app and want someone to build it with you, <a href="https://neemii.dev/#contact">tell me about your project</a>.</p>
<hr />
<p><em>Originally published at <a href="https://neemii.dev/blog/flutter-json-parsing/">neemii.dev</a>. I'm Muhammad Naeem, a Flutter developer with 10+ apps on the App Store and Google Play. More free tools for Flutter developers: <a href="https://neemii.dev/tools/">neemii.dev/tools</a>.</em></p>
]]></content:encoded></item><item><title><![CDATA[Flutter JSON Parsing: fromJson, Null Safety and Code Generation]]></title><description><![CDATA[How to parse JSON in Flutter: jsonDecode, fromJson/toJson models, null safety, nested lists, json_serializable vs freezed, and the runtime errors you will…]]></description><link>https://neemii.hashnode.dev/flutter-json-parsing-fromjson-null-safety-and-code-generation</link><guid isPermaLink="true">https://neemii.hashnode.dev/flutter-json-parsing-fromjson-null-safety-and-code-generation</guid><category><![CDATA[Flutter]]></category><category><![CDATA[Dart]]></category><category><![CDATA[json]]></category><category><![CDATA[Mobile Development]]></category><dc:creator><![CDATA[Muhammad Naeem]]></dc:creator><pubDate>Thu, 19 Nov 2026 05:40:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6afe88d80a8396bd81928ac1/2889de4c-5e2f-42bc-a69f-bdfbbebabaea.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<hr />
<p>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.</p>
<p>This post covers both, in the order you'll meet them: <code>jsonDecode</code>, a hand-written model, the null safety traps, nested objects and lists, <code>json_serializable</code>, <code>freezed</code>, and the error messages that show up when something doesn't match.</p>
<h2>Step 1: jsonDecode gives you dynamic data</h2>
<p><code>jsonDecode</code> from <code>dart:convert</code> turns a JSON string into plain Dart values: <code>Map&lt;String, dynamic&gt;</code> for objects, <code>List&lt;dynamic&gt;</code> for arrays, and <code>String</code>, <code>int</code>, <code>double</code>, <code>bool</code> or <code>null</code> for the rest.</p>
<pre><code class="language-dart">import 'dart:convert';

void main() {
  const body = '{"id": 7, "name": "Ayesha", "email": null}';
  final data = jsonDecode(body) as Map&lt;String, dynamic&gt;;
  print(data['name']); // Ayesha
  print(data['id'].runtimeType); // int
}
</code></pre>
<p>You could pass <code>data</code> around your app and read <code>data['name']</code> everywhere. Don't. Every read is untyped, a typo in a key returns <code>null</code> instead of a compile error, and when the API changes you find out from a crash report. Convert it to a class once, at the edge of your app.</p>
<h2>Step 2: a model class with fromJson and toJson</h2>
<p>The standard pattern is a <code>fromJson</code> factory constructor and a <code>toJson</code> method:</p>
<pre><code class="language-dart">class User {
  const User({required this.id, required this.name, this.email});

  final int id;
  final String name;
  final String? email;

  factory User.fromJson(Map&lt;String, dynamic&gt; json) =&gt; User(
        id: json['id'] as int,
        name: json['name'] as String,
        email: json['email'] as String?,
      );

  Map&lt;String, dynamic&gt; toJson() =&gt; {
        'id': id,
        'name': name,
        'email': email,
      };
}
</code></pre>
<p>Usage:</p>
<pre><code class="language-dart">final user = User.fromJson(data);
print(user.email); // null
print(jsonEncode(user.toJson())); // {"id":7,"name":"Ayesha","email":null}
</code></pre>
<p>The <code>as</code> casts are the important part. They are where the type check happens, and they are where your app will throw if the API sends something you didn't expect. That is a good thing: it fails at the parsing line, with a clear message, instead of three screens later.</p>
<p>If you don't want to type these classes by hand, paste a real response into my <a href="https://neemii.dev/tools/json-to-dart/">JSON to Dart converter</a>. It produces this same style of model (plain Dart, <code>json_serializable</code> or <code>freezed</code>), runs in your browser, and doesn't send your JSON anywhere.</p>
<h2>Null safety: where most parsing bugs come from</h2>
<p>Dart's null safety only protects you after the data is inside a typed field. The cast from <code>dynamic</code> is where you decide what's allowed to be null, and getting that decision wrong is the most common source of crashes.</p>
<h3>int vs double</h3>
<p>JSON has one number type. Dart has two. <code>jsonDecode('450')</code> gives you an <code>int</code>, and <code>jsonDecode('450.0')</code> gives you a <code>double</code>. Many APIs send prices as <code>450</code> one day and <code>450.5</code> the next, so this will eventually crash on a phone:</p>
<pre><code class="language-dart">price: json['price'] as double, // throws when the API sends 450
</code></pre>
<p>Read every <code>double</code> through <code>num</code> instead:</p>
<pre><code class="language-dart">price: (json['price'] as num).toDouble(),
</code></pre>
<p>One detail that makes this bug sneaky: on Flutter web compiled to JavaScript (the default build), <code>int</code> and <code>double</code> are both JavaScript numbers, so <code>450 as double</code> succeeds. The same line compiled with <code>dart compile js</code> printed <code>450</code>, while the Dart VM threw. If you test mainly on web, you can ship this bug to Android and iOS without seeing it once.</p>
<h3>Missing keys and null values</h3>
<p>Reading a key that isn't in the map returns <code>null</code>, the same as a key whose value is <code>null</code>. So <code>json['email'] as String?</code> handles both cases. A field that's required in your class but missing from the response throws:</p>
<pre><code class="language-text">type 'Null' is not a subtype of type 'String' in type cast
</code></pre>
<p>For each field, decide which of three things it is:</p>
<ol>
<li><strong>Always present</strong>: non-nullable type, plain cast (<code>as String</code>).</li>
<li><strong>Sometimes missing, and null means something</strong>: nullable type (<code>String?</code>, <code>as String?</code>).</li>
<li><strong>Sometimes missing, but there's a sensible default</strong>: nullable cast plus <code>??</code>.</li>
</ol>
<pre><code class="language-dart">status: json['status'] as String? ?? 'pending',
</code></pre>
<p>Don't make everything nullable just to stop crashes. You'll trade one crash at parse time for <code>!</code> operators and null checks spread through your UI code. Be strict where the API contract is strict, and loose only where it really is optional.</p>
<blockquote>
<p><strong>From my own work:</strong> on a government survey app I'm working on (I can't share details), records were getting stuck on some enumerators' devices and never reached the server. I went through the Postman responses, the Grafana logs and the field notes, and found the cause: in a few scenarios a record was missing an ID in the local database, so the JSON the app sent was not what the server expected, and the server rejected it every time the app retried. Making the parser more lenient would only have hidden the problem. Instead I added an auto-repair step that restores any missing survey ID in the local database before upload, so the server accepts the JSON and the stuck records go through. The lesson: when JSON fails, check the data you're serialising, not just the parsing code.</p>
</blockquote>
<h3>When the API sends the wrong type</h3>
<p>Some backends send <code>"id": "42"</code> in one endpoint and <code>"id": 42</code> in another. If you can't get the backend fixed, read it with a small helper instead of a cast:</p>
<pre><code class="language-dart">int readInt(Object? v) =&gt; switch (v) {
      int i =&gt; i,
      num n =&gt; n.toInt(),
      String s =&gt; int.parse(s),
      _ =&gt; throw FormatException('Expected an int, got $v'),
    };
</code></pre>
<p>Keep these helpers few and deliberate. Each one hides a backend inconsistency that someone should eventually fix.</p>
<h2>Nested objects and lists</h2>
<p>Real responses are nested. Here's an order with a customer object, a list of items and a list of strings:</p>
<pre><code class="language-json">{
  "id": 1042,
  "total": 450,
  "customer": {"name": "Sara", "phone": null},
  "items": [
    {"title": "Chai", "qty": 2, "price": 150},
    {"title": "Samosa", "qty": 3, "price": 50.0}
  ],
  "tags": ["express", "paid"]
}
</code></pre>
<p>Each nested object gets its own class with its own <code>fromJson</code>. Lists are decoded as <code>List&lt;dynamic&gt;</code>, so you map each element:</p>
<pre><code class="language-dart">factory Order.fromJson(Map&lt;String, dynamic&gt; json) =&gt; Order(
      id: json['id'] as int,
      status: json['status'] as String? ?? 'pending',
      total: (json['total'] as num).toDouble(),
      customer: Customer.fromJson(json['customer'] as Map&lt;String, dynamic&gt;),
      items: (json['items'] as List&lt;dynamic&gt;)
          .map((e) =&gt; OrderItem.fromJson(e as Map&lt;String, dynamic&gt;))
          .toList(),
      tags: (json['tags'] as List&lt;dynamic&gt;? ?? const [])
          .map((e) =&gt; e as String)
          .toList(),
      coupon: json['coupon'] as String?,
    );

Map&lt;String, dynamic&gt; toJson() =&gt; {
      'id': id,
      'status': status,
      'total': total,
      'customer': customer.toJson(),
      'items': items.map((e) =&gt; e.toJson()).toList(),
      'tags': tags,
      'coupon': coupon,
    };
</code></pre>
<p><code>Customer</code> and <code>OrderItem</code> follow the same pattern as <code>User</code> above, with <code>OrderItem.price</code> read as <code>(json['price'] as num).toDouble()</code>. Note that <code>toJson</code> calls <code>toJson()</code> on the nested objects too, so you get plain maps all the way down.</p>
<h3>When the top level is a list</h3>
<p>If the endpoint returns an array, cast the decoded value to <code>List&lt;dynamic&gt;</code>:</p>
<pre><code class="language-dart">final users = (jsonDecode(body) as List&lt;dynamic&gt;)
    .map((e) =&gt; User.fromJson(e as Map&lt;String, dynamic&gt;))
    .toList();
</code></pre>
<p>Many APIs wrap the list instead: <code>{"data": [...], "page": 1}</code>. Then you cast to a map first and read the list from it:</p>
<pre><code class="language-dart">final map = jsonDecode(body) as Map&lt;String, dynamic&gt;;
final users = (map['data'] as List&lt;dynamic&gt;)
    .map((e) =&gt; User.fromJson(e as Map&lt;String, dynamic&gt;))
    .toList();
</code></pre>
<h3>Large responses</h3>
<p>Decoding a big response on the main isolate can drop frames. Move the parsing to another isolate with <code>Isolate.run</code> (or Flutter's <code>compute</code>):</p>
<pre><code class="language-dart">List&lt;User&gt; parseUsers(String body) =&gt; (jsonDecode(body) as List&lt;dynamic&gt;)
    .map((e) =&gt; User.fromJson(e as Map&lt;String, dynamic&gt;))
    .toList();

final users = await Isolate.run(() =&gt; parseUsers(body));
</code></pre>
<p>The closure and what it captures (here, the <code>body</code> string) are copied into the new isolate, so keep it small and self-contained. Only do this when you've seen jank on a real device; for small payloads it adds overhead without any benefit.</p>
<h2>json_serializable: let the generator write fromJson</h2>
<p>Writing models by hand is fine for a few classes. Past that, the casts get repetitive and a renamed field is easy to miss in <code>toJson</code>. <code>json_serializable</code> generates both methods from annotations.</p>
<p>Add the packages:</p>
<pre><code class="language-text">flutter pub add json_annotation dev:build_runner dev:json_serializable
</code></pre>
<p>Then annotate the model and point it at the file that will be generated:</p>
<pre><code class="language-dart">import 'package:json_annotation/json_annotation.dart';

part 'product.g.dart';

@JsonSerializable(explicitToJson: true)
class Product {
  const Product({
    required this.id,
    required this.title,
    required this.price,
    this.imageUrl,
    this.inStock = true,
    required this.variants,
  });

  final int id;
  final String title;
  final double price;

  @JsonKey(name: 'image_url')
  final String? imageUrl;

  @JsonKey(name: 'in_stock')
  final bool inStock;

  final List&lt;Variant&gt; variants;

  factory Product.fromJson(Map&lt;String, dynamic&gt; json) =&gt;
      _$ProductFromJson(json);

  Map&lt;String, dynamic&gt; toJson() =&gt; _$ProductToJson(this);
}
</code></pre>
<p><code>Variant</code> is another <code>@JsonSerializable()</code> class with the same two one-line methods. Generate the code:</p>
<pre><code class="language-text">dart run build_runner build --delete-conflicting-outputs
</code></pre>
<p>Use <code>watch</code> instead of <code>build</code> to regenerate on every save. The generated <code>product.g.dart</code> reads numbers safely for you:</p>
<pre><code class="language-dart">Product _$ProductFromJson(Map&lt;String, dynamic&gt; json) =&gt; Product(
  id: (json['id'] as num).toInt(),
  title: json['title'] as String,
  price: (json['price'] as num).toDouble(),
  imageUrl: json['image_url'] as String?,
  inStock: json['in_stock'] as bool? ?? true,
  variants: (json['variants'] as List&lt;dynamic&gt;)
      .map((e) =&gt; Variant.fromJson(e as Map&lt;String, dynamic&gt;))
      .toList(),
);
</code></pre>
<p>Things worth knowing:</p>
<ul>
<li><strong><code>explicitToJson: true</code></strong> matters for nested objects. Without it, <code>toJson()</code> puts the <code>Variant</code> objects themselves in the map, not maps. <code>jsonEncode</code> still works because it calls <code>toJson()</code> on them, but anything else that expects a plain map (a local database, a test comparing maps) will not.</li>
<li><strong>Default values</strong> in the constructor (<code>this.inStock = true</code>) are used when the key is missing or null.</li>
<li><strong>Project-wide settings</strong> go in <code>build.yaml</code> at the project root, so you don't repeat them on every class:</li>
</ul>
<pre><code class="language-yaml">targets:
  $default:
    builders:
      json_serializable:
        options:
          explicit_to_json: true
          field_rename: snake
</code></pre>
<p>With <code>field_rename: snake</code>, a Dart field <code>fullName</code> maps to the JSON key <code>full_name</code> without a <code>@JsonKey</code> on every field.</p>
<p>The cost is the build step: a <code>part</code> directive in every model, generated files in your repo (or a build step in CI), and a few seconds of waiting after each model change.</p>
<h2>freezed: when you want more than JSON</h2>
<p><code>freezed</code> is a different kind of tool. It generates immutable data classes: <code>copyWith</code>, <code>==</code> and <code>hashCode</code> based on values, <code>toString</code>, and sealed unions. For JSON it hands off to <code>json_serializable</code>, so you install both.</p>
<pre><code class="language-dart">import 'package:freezed_annotation/freezed_annotation.dart';

part 'product.freezed.dart';
part 'product.g.dart';

@freezed
abstract class Product with _$Product {
  const factory Product({
    required int id,
    required String title,
    required double price,
    @JsonKey(name: 'image_url') String? imageUrl,
    @JsonKey(name: 'in_stock') @Default(true) bool inStock,
  }) = _Product;

  factory Product.fromJson(Map&lt;String, dynamic&gt; json) =&gt;
      _$ProductFromJson(json);
}
</code></pre>
<p>With that you get <code>product.copyWith(price: 1999)</code> and <code>a == b</code> comparing values, which is what state management (Bloc, Riverpod) wants when it decides whether to rebuild.</p>
<p>Two notes for current versions (freezed 3.x). The class must be declared <code>abstract</code> (or <code>sealed</code> for unions), which older tutorials don't show. And <code>@JsonKey</code> on constructor parameters triggers the analyzer warning <code>invalid_annotation_target</code>; freezed's own docs recommend turning it off in <code>analysis_options.yaml</code>:</p>
<pre><code class="language-yaml">analyzer:
  errors:
    invalid_annotation_target: ignore
</code></pre>
<p>Is it worth it? If you only need to parse API responses and show them, no: <code>json_serializable</code> alone is less generated code and fewer concepts. <code>freezed</code> earns its place when your models are also your app state, when you update them with <code>copyWith</code> a lot, or when you want sealed classes like <code>Loading | Loaded | Error</code> with exhaustive <code>switch</code>.</p>
<h2>Which approach for which app</h2>
<table>
<thead>
<tr>
<th>Situation</th>
<th>Approach</th>
</tr>
</thead>
<tbody><tr>
<td>Prototype, small app, a handful of models</td>
<td>Hand-written models (or generated once with the <a href="https://neemii.dev/tools/json-to-dart/">converter</a>)</td>
</tr>
<tr>
<td>Many models, a team, an API that keeps changing</td>
<td><code>json_serializable</code></td>
</tr>
<tr>
<td>Models are also app state; you need <code>copyWith</code>, equality, unions</td>
<td><code>freezed</code> + <code>json_serializable</code></td>
</tr>
</tbody></table>
<p>You can mix them. Starting with hand-written models and moving to <code>json_serializable</code> later is a mechanical change, because the public API (<code>fromJson</code> and <code>toJson</code>) stays the same. Code generation is still the standard way to do this in Dart: the macros experiment that promised <code>@JsonCodable</code> without <code>build_runner</code> was stopped by the Dart team in early 2025.</p>
<blockquote>
<p><strong>What I use:</strong> in my own client apps I write plain <code>fromJson</code>/<code>toJson</code> by hand. It keeps the models readable and adds no code generation step to the build. I then check each model against the official Flutter and Dart documentation, and use AI tools as a second reviewer to catch a missed null case or wrong cast.</p>
</blockquote>
<h2>Common errors and what they mean</h2>
<p>These are the exact messages from the Dart VM (which is what runs your app on Android and iOS), reproduced with the code next to each one.</p>
<p><strong><code>type 'int' is not a subtype of type 'double' in type cast</code></strong>
You cast a whole number to <code>double</code>: <code>json['price'] as double</code> with <code>"price": 450</code>. Fix: <code>(json['price'] as num).toDouble()</code>. Without the <code>as</code> (for example <code>final double price = json['price'];</code>) the message is the same minus "in type cast".</p>
<p><strong><code>type 'Null' is not a subtype of type 'String' in type cast</code></strong>
A field you declared non-nullable was <code>null</code> or missing. Check the raw response. Either make the field nullable, give it a default with <code>??</code>, or fix the backend.</p>
<p><strong><code>type 'List&lt;dynamic&gt;' is not a subtype of type 'List&lt;String&gt;' in type cast</code></strong>
<code>json['tags'] as List&lt;String&gt;</code>. A decoded JSON list is always <code>List&lt;dynamic&gt;</code>, even if every element is a string. Fix: <code>(json['tags'] as List&lt;dynamic&gt;).map((e) =&gt; e as String).toList()</code>.</p>
<p><strong><code>type '_Map&lt;String, dynamic&gt;' is not a subtype of type 'List&lt;dynamic&gt;' in type cast</code></strong>
You expected an array at the top level, but the API wraps it: <code>{"data": [...]}</code>. Cast to <code>Map&lt;String, dynamic&gt;</code> first and read the list from <code>map['data']</code>. <code>_Map</code> is just the private class <code>jsonDecode</code> uses for objects.</p>
<p><strong><code>type '_Map&lt;String, dynamic&gt;' is not a subtype of type 'Map&lt;String, String&gt;' in type cast</code></strong>
Same root cause as the list case: decoded maps are always <code>Map&lt;String, dynamic&gt;</code>. Cast to that and convert the values, or better, write a class for the nested object.</p>
<p><strong><code>type 'String' is not a subtype of type 'int' in type cast</code></strong>
The API sent <code>"id": "42"</code>. Fix the backend if you can; otherwise use a helper like <code>readInt</code> above.</p>
<p><strong><code>type 'String' is not a subtype of type 'int' of 'index'</code></strong>
You indexed a list with a string key: <code>list['id']</code> where <code>list</code> is the decoded array. Take an element first (<code>list[0]['id']</code>), or map the list into models.</p>
<p><strong><code>FormatException: Unexpected character (at character 1)</code></strong>
The body isn't JSON at all. Most often it's an HTML error page from a proxy, a login redirect, or a 500. Check the status code before calling <code>jsonDecode</code>. An empty body gives <code>FormatException: Unexpected end of input (at character 1)</code>.</p>
<h2>Summary</h2>
<ul>
<li>Decode once with <code>jsonDecode</code>, convert to typed models right away, and keep <code>dynamic</code> out of your widgets.</li>
<li>Read doubles through <code>num</code>. Decide per field what's required, optional or defaulted.</li>
<li>Map lists element by element; cast nested objects to <code>Map&lt;String, dynamic&gt;</code>.</li>
<li>Move to <code>json_serializable</code> when the models multiply, and add <code>freezed</code> when they become app state.</li>
</ul>
<p>If you want the boilerplate done for you, paste your API response into the free <a href="https://neemii.dev/tools/json-to-dart/">JSON to Dart model converter</a>. It handles nullable fields, int/double, ISO dates as <code>DateTime</code>, snake_case keys and nested lists, and outputs plain Dart, <code>json_serializable</code> or <code>freezed</code>. And if you're building a Flutter app and want someone to build it with you, <a href="https://neemii.dev/#contact">tell me about your project</a>.</p>
<hr />
<p><em>Originally published at <a href="https://neemii.dev/blog/flutter-json-parsing/">neemii.dev</a>. I'm Muhammad Naeem, a Flutter developer with 10+ apps on the App Store and Google Play. More free tools for Flutter developers: <a href="https://neemii.dev/tools/">neemii.dev/tools</a>.</em></p>
]]></content:encoded></item></channel></rss>