Menu
CoddyTech

날씨 앱: 현재 날씨

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

이 섹션에서는 날씨 앱이라는 완전한 앱을 만들어 봅니다. 다음 다섯 번의 수업에 걸쳐 한 도시의 현재 날씨와 향후 3일간의 날씨, 각각의 날씨 아이콘, 다시 시도 버튼이 있는 오류 화면, 도시 선택기를 표시합니다.

실습용 API에는 세 도시가 등록되어 있습니다. /weather/lisbon은 다음과 같이 응답합니다.

{
  "city": "Lisbon",
  "temperature": 21,
  "condition": "Sunny",
  "forecast": [ ... ]
}

화면의 상단부터 시작해, 이미 배운 단계를 따라가 봅시다. 데이터용 클래스, 데이터를 가져와 디코딩하는 함수, initState에서 한 번 생성하는 future, 그리고 세 가지 상태를 처리하는 FutureBuilder입니다. 파일 하단의 Weather 및 DayForecast 클래스와 해당 클래스의 fromJson은 미리 작성되어 있습니다. 이 수업에서는 현재 날씨를 표시하고, 예보는 다음 수업에서 다룹니다.

challenge icon

챌린지

어려움

리스본의 날씨를 표시하세요:

  • loadWeather는 /weather/lisbon을 가져와 Weather.fromJson(jsonDecode(body))를 반환합니다
  • initState에서 미래 객체를 한 번 만듭니다
  • FutureBuilder<Weather>는 로드 중에 스피너를 표시하고, 실패하면 Could not load: 와 오류를 표시합니다
  • 데이터가 있으면 도시(크기 32), 도 기호가 붙은 온도 21°(크기 72, 굵게), 상태(크기 24)를 Column에 표시합니다

직접 해보기

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

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

  @override
  State<WeatherScreen> createState() => _WeatherScreenState();
}

class _WeatherScreenState extends State<WeatherScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Weather')),
      body: const Center(
        child: Text('The weather goes here'),
      ),
    );
  }
}

class Weather {
  Weather({
    required this.city,
    required this.temperature,
    required this.condition,
    required this.forecast,
  });

  final String city;
  final int temperature;
  final String condition;
  final List<DayForecast> forecast;

  factory Weather.fromJson(Map<String, dynamic> json) {
    final days = json['forecast'] as List<dynamic>;
    return Weather(
      city: json['city'] as String,
      temperature: json['temperature'] as int,
      condition: json['condition'] as String,
      forecast: days
          .map((day) => DayForecast.fromJson(day as Map<String, dynamic>))
          .toList(),
    );
  }
}

class DayForecast {
  DayForecast({
    required this.date,
    required this.condition,
    required this.high,
    required this.low,
  });

  final DateTime date;
  final String condition;
  final int high;
  final int low;

  factory DayForecast.fromJson(Map<String, dynamic> json) {
    return DayForecast(
      date: DateTime.parse(json['date'] as String),
      condition: json['condition'] as String,
      high: json['high'] as int,
      low: json['low'] as int,
    );
  }
}
quiz icon실력 점검

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

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

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