Flutter 플러터 날씨 정보 가져오기 앱 간단 구현 Weather

반응형

Flutter 플러터 날씨 정보 가져오기 앱 간단 구현 Weather

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Weather App',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: WeatherPage(),
    );
  }
}

class WeatherPage extends StatefulWidget {
  @override
  _WeatherPageState createState() => _WeatherPageState();
}

class _WeatherPageState extends State<WeatherPage> {
  String _cityName = 'New York';
  String _apiKey = 'YOUR_API_KEY'; // Replace this with your OpenWeatherMap API key
  String _apiUrl =
      'http://api.openweathermap.org/data/2.5/weather?q=$_cityName&appid=$_apiKey&units=metric';

  var _weatherData;

  Future<void> fetchWeatherData() async {
    final response = await http.get(Uri.parse(_apiUrl));
    final decodedResponse = json.decode(response.body);
    setState(() {
      _weatherData = decodedResponse;
    });
  }

  @override
  void initState() {
    super.initState();
    fetchWeatherData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Weather App'),
      ),
      body: _weatherData == null
          ? Center(child: CircularProgressIndicator())
          : Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  'City: $_cityName',
                  style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
                ),
                SizedBox(height: 10),
                Text(
                  'Temperature: ${_weatherData['main']['temp']} °C',
                  style: TextStyle(fontSize: 18),
                ),
                SizedBox(height: 10),
                Text(
                  'Description: ${_weatherData['weather'][0]['description']}',
                  style: TextStyle(fontSize: 18),
                ),
              ],
            ),
    );
  }
}
반응형