Menu
CoddyTech

Missing JSON Fields

Part of the Data and the Network section of Coddy's Flutter journey. Lesson 19 of 27.

Real data has gaps. In /books, two books have a "subtitle" and Pride and Prejudice has none. For a key that is not there, json['subtitle'] gives null, and null as String fails: the whole list fails to load with type 'Null' is not a subtype of type 'String'.

A type with a ? after it can also hold null. String? is "a string, or nothing":

final String? subtitle;

subtitle: json['subtitle'] as String?,

Dart then makes you deal with the gap wherever you use it. ?? gives a fallback for null:

Text(book.subtitle ?? 'No subtitle')

You could also write book.subtitle!, which tells Dart "trust me, it is not null". For data from a server that is a promise you cannot keep: on the book with no subtitle, ! crashes the screen. Keep ! for places you checked, like snapshot.data! after hasData.

challenge icon

Challenge

Medium

The shelf fails to load, because one book has no subtitle. Make the subtitle optional:

  • the field is a String?, read as String?
  • the list shows No subtitle for a book without one

Try it yourself

import 'dart:convert';

import 'package:flutter/material.dart';

import 'api.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: BooksScreen(),
    );
  }
}

class BooksScreen extends StatefulWidget {
  const BooksScreen({super.key});

  @override
  State<BooksScreen> createState() => _BooksScreenState();
}

class _BooksScreenState extends State<BooksScreen> {
  late Future<List<Book>> _books;

  @override
  void initState() {
    super.initState();
    _books = loadBooks();
  }

  Future<List<Book>> loadBooks() async {
    final body = await fetch('/books');
    final items = jsonDecode(body) as List<dynamic>;
    return items.map((item) => Book.fromJson(item as Map<String, dynamic>)).toList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Books')),
      body: FutureBuilder<List<Book>>(
        future: _books,
        builder: (context, snapshot) {
          if (snapshot.hasError) {
            return Center(child: Text('Could not load: ${snapshot.error}'));
          }
          if (snapshot.hasData) {
            final books = snapshot.data!;
            return ListView.builder(
              itemCount: books.length,
              itemBuilder: (context, index) {
                final book = books[index];
                return ListTile(
                  title: Text(book.title),
                  subtitle: Text(book.subtitle),
                );
              },
            );
          }
          return const Center(child: CircularProgressIndicator());
        },
      ),
    );
  }
}

class Book {
  Book({required this.title, required this.subtitle});

  final String title;
  final String subtitle;

  factory Book.fromJson(Map<String, dynamic> json) {
    return Book(
      title: json['title'] as String,
      subtitle: json['subtitle'] as String,
    );
  }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Data and the Network

Practice on your own: Online Flutter compiler