728x90
반응형
사용자 위치를 기반으로 현재 위치의 날씨를 보여주는 건 날씨 앱의 핵심 기능 중 하나다.
이번 글에서는 Flutter에서 위치 권한 요청부터 GPS 정보 추출, 그리고 해당 좌표를 기반으로 OpenWeather API에 날씨 요청까지의 전체 흐름을 구현해본다.
📦 필요 패키지 설치
// pubspec.yaml
dependencies:
geolocator: ^10.1.0
http: ^0.13.5
geolocator
는 GPS 위치를 가져오는 대표적인 패키지다.
🔑 Android/iOS 권한 설정
✅ Android
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application>
...
<meta-data android:name="flutterEmbedding" android:value="2"/>
</application>
✅ iOS
// Info.plist
<key>NSLocationWhenInUseUsageDescription</key>
<string>앱이 현재 위치를 사용합니다.</string>
권한 설정이 누락되면 앱이 위치 정보를 가져올 수 없으니 주의!
📍 현재 위치 가져오기
import 'package:geolocator/geolocator.dart';
Future<Position> getCurrentLocation() async {
bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
throw Exception('GPS 비활성화됨');
}
LocationPermission permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.deniedForever) {
throw Exception('위치 권한 영구 거부됨');
}
}
return await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high,
);
}
권한을 먼저 확인하고, 문제가 없을 때 위치를 요청해야 한다.
📡 위도/경도로 날씨 요청하기
Future<Map<String, dynamic>> fetchWeatherByLocation(double lat, double lon) async {
final apiKey = 'YOUR_API_KEY';
final url =
'https://api.openweathermap.org/data/2.5/weather?lat=$lat&lon=$lon&appid=$apiKey&units=metric';
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
return jsonDecode(response.body);
} else {
throw Exception('날씨 요청 실패');
}
}
OpenWeather API는 lat
, lon
을 인자로 받을 수 있다.
📱 통합: 위치 기반 날씨 UI
FutureBuilder(
future: getCurrentLocation().then((pos) =>
fetchWeatherByLocation(pos.latitude, pos.longitude)),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
} else if (snapshot.hasError) {
return Text("오류 발생: ${snapshot.error}");
} else {
final data = snapshot.data!;
return Column(
children: [
Text("${data['name']}", style: TextStyle(fontSize: 24)),
Text("${data['main']['temp']}°C", style: TextStyle(fontSize: 48)),
],
);
}
},
)
위치 → 좌표 → 날씨 요청 → 화면 출력 4단계 흐름이 정리되면 기능이 완성된다.
🧘 마무리하며
Flutter 날씨 앱의 핵심은 단순히 정보를 보여주는 것이 아니라 내 주변의 현재 상황을 바로 보여주는 것이다.
위치 기반 기능을 추가하면 사용자 경험은 훨씬 더 스마트해진다.
이제 앱이 사용자의 위치를 먼저 알아챈다.
✍️ 이 글은 터미널 밖으로 나온 개발자의 Flutter 날씨 앱 만들기 여정입니다.
728x90
반응형
'Flutter > Flutter 날씨 앱 만들기' 카테고리의 다른 글
온도, 습도, 바람 정보 시각화하기 (0) | 2025.06.13 |
---|---|
날씨에 따라 배경 바꾸기 — 애니메이션과 날씨 감성 UI (2) | 2025.06.12 |
시간대별/주간 날씨 예보 표시 (0) | 2025.06.11 |
OpenWeather API 연동하기 — 실시간 날씨 받아오기 (0) | 2025.06.09 |
날씨 앱 UI 디자인 — 깔끔하고 직관적인 레이아웃 (0) | 2025.06.08 |