Menu
CoddyTech

JSON 값과 as

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

JSON 맵의 값은 dynamic입니다. Dart는 이 값이 무엇인지 알지 못하므로 이 값으로 무엇을 하든 검사하지 않고, 편집기도 도움을 줄 수 없습니다. 서버가 무엇을 보내는지 알고 있습니다. age는 숫자이고, isPro는 true 또는 false입니다. as로 명시하세요.

final age = user['age'] as int;
final isPro = user['isPro'] as bool;

as는 바로 그 자리에서 값을 검사합니다. 그 이후로 age는 int이고 isPro는 bool이며, Dart는 이 값들을 그렇게 취급합니다. 서버가 다른 값을 보냈다면, 앱은 한참 떨어진 곳이 아니라 해당 줄에서 두 유형의 이름을 모두 알려주는 메시지와 함께 실패합니다.

JSON 값은 다음과 같이 Dart 유형에 대응합니다. 따옴표로 묶인 텍스트는 String이고, 정수는 int이며, 소수점이 있는 숫자는 double이고, true 또는 false는 bool입니다. true에는 따옴표가 없다는 점에 유의하세요. 이것은 bool이지, 텍스트 'true'가 아닙니다.

challenge icon

챌린지

중급

프로필을 더 많이 표시하세요. 빌더에서 각 값을 as를 사용해 읽으세요. name과 email은 String으로, age는 int로, isPro는 bool로 읽습니다. 그런 다음 이메일 아래에 다음을 추가하세요.

  • 28 years old, age를 사용해 만듭니다.
  • isPro가 true일 때는 Pro member를, 그렇지 않을 때는 Free plan을 표시합니다.

직접 해보기

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: ProfileScreen(),
    );
  }
}

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

  @override
  State<ProfileScreen> createState() => _ProfileScreenState();
}

class _ProfileScreenState extends State<ProfileScreen> {
  late Future<Map<String, dynamic>> _user;

  @override
  void initState() {
    super.initState();
    _user = loadUser();
  }

  Future<Map<String, dynamic>> loadUser() async {
    final body = await fetch('/user');
    return jsonDecode(body);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Profile')),
      body: Center(
        child: FutureBuilder<Map<String, dynamic>>(
          future: _user,
          builder: (context, snapshot) {
            if (snapshot.hasError) {
              return Text('Could not load: ${snapshot.error}');
            }
            if (snapshot.hasData) {
              final user = snapshot.data!;
              return Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    user['name'],
                    style: const TextStyle(fontSize: 28, fontWeight: FontWeight.bold),
                  ),
                  const SizedBox(height: 8),
                  Text(user['email'], style: const TextStyle(fontSize: 18)),
                ],
              );
            }
            return const CircularProgressIndicator();
          },
        ),
      ),
    );
  }
}
quiz icon실력 점검

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

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

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