A List From JSON
Part of the Data and the Network section of Coddy's Flutter journey. Lesson 18 of 27.
Many answers are lists: every book, every message, every day of a forecast. In JSON a list is written in square brackets, and here each item is an object:
[
{"title": "Frankenstein", "author": "Mary Shelley"},
{"title": "Pride and Prejudice", "author": "Jane Austen"}
]jsonDecode turns square brackets into a List. Its items are dynamic too, so say what you expect with as: List<dynamic> for the list, Map<String, dynamic> for each item.
Then turn every item into a Book with map, and collect the results with toList():
final items = jsonDecode(body) as List<dynamic>;
return items
.map((item) => Book.fromJson(item as Map<String, dynamic>))
.toList();map alone gives a lazy Iterable, not a List, which is why toList() is there. The screen then has a List<Book> for ListView.builder.
Challenge
MediumThe shelf shows only the first book. Make loadBooks turn every item of the list into a Book, with items.map(...) and .toList().
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 [Book.fromJson(items[0] as Map<String, dynamic>)];
}
@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.author),
);
},
);
}
return const Center(child: CircularProgressIndicator());
},
),
);
}
}
class Book {
Book({required this.title, required this.author});
final String title;
final String author;
factory Book.fromJson(Map<String, dynamic> json) {
return Book(
title: json['title'] as String,
author: json['author'] as String,
);
}
}
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