Menu
CoddyTech

누락된 JSON 필드

Coddy Flutter 여정의 데이터와 네트워크 섹션에 포함된 레슨. 27개 중 19번째.

실제 데이터에는 누락된 값이 있습니다. /books에서 두 권의 책에는 "subtitle"이 있고, 오만과 편견에는 없습니다. 없는 키에 대해 json['subtitle']은 null을 반환하며, null as String은 실패합니다. 전체 목록이 type 'Null' is not a subtype of type 'String' 오류와 함께 로드되지 않습니다.

타입 뒤에 ?를 붙이면 null도 담을 수 있습니다. String?은 "문자열이거나 아무것도 없음"을 뜻합니다.

final String? subtitle;

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

그러면 Dart는 해당 값을 사용하는 모든 곳에서 누락된 값을 처리하도록 합니다. ??는 null일 때 대체값을 제공합니다.

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

book.subtitle!이라고 쓸 수도 있습니다. 이는 Dart에 "널이 아니라고 믿어도 돼"라고 알립니다. 서버에서 받은 데이터에 대해서는 지킬 수 없는 약속입니다. 부제가 없는 책에서 !를 사용하면 화면이 충돌합니다. hasData를 확인한 뒤의 snapshot.data!처럼 직접 확인한 곳에서만 !를 사용하세요.

challenge icon

챌린지

중급

책 한 권에 부제가 없어 책 목록을 불러오지 못합니다. 부제를 선택 사항으로 만드세요:

  • 필드는 String?이고, as String?으로 읽습니다
  • 부제가 없는 책에는 목록에 No subtitle이 표시됩니다

직접 해보기

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 icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

데이터와 네트워크의 모든 레슨

직접 연습해 보세요: 온라인 Flutter 컴파일러