오늘은 http & json 에 대해서 알아보겠습니다.
개발환경 : 윈도우11, 안드로이드 스튜디오, flutter 2.8.1
소스코드 위치 - https://github.com/mike-bskim/weather/releases/tag/json
먼저 준비 작업
1. 패키지 추가
http: ^0.13.4
2. AndroidManifest.xml 파일에 permission 추가
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.weather">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- Required to fetch data from the internet. -->
<uses-permission android:name="android.permission.INTERNET" /> 이 부분 추가
loading.dart 파일 수정
import 'package:http/http.dart' as http; // 패키지는 가독성을 위해서 별명추가함
class _LoadingState extends State<Loading> {
@override
void initState() {
// TODO: implement initState
super.initState();
getLocation();
fetchData();
}
void getLocation() async {
// 오류 방지를 위한 try/catch 구문추가
try {
LocationPermission permission = await Geolocator.requestPermission();
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high);
debugPrint(position.toString());
} catch (e) {
debugPrint('internet connection Error');
}
}
// 이부분이 핵심추가 사항
void fetchData() async {
// 샘플주소를 가지고 parsing 테스트
http.Response response = await http.get(Uri.parse(
'https://samples.openweathermap.org/data/2.5/weather?q=London&appid=b1b15e88fa797225412429c1c50c122a1'));
if (response.statusCode == 200) {
String jsonData = response.body;
// 특정 데이터만 추출
var myJson = jsonDecode(jsonData)['weather'][0]['description'];
debugPrint(myJson);
} else {}
// body 데이터 전체 출력
debugPrint(response.body.toString());
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () {
debugPrint('ElevatedButton clicked~~');
fetchData();
},
child: const Text(
'Get my location',
style: TextStyle(color: Colors.white),
),
),
),
);
}
}
콘솔로 출력되는 내용
I/flutter ( 9849): ElevatedButton clicked~~
I/flutter ( 9849): light intensity drizzle
I/flutter ( 9849): {"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":300,"main":"Drizzle","description":"light intensity drizzle","icon":"09d"}],"base":"stations","main":{"temp":280.32,"pressure":1012,"humidity":81,"temp_min":279.15,"temp_max":281.15},"visibility":10000,"wind":{"speed":4.1,"deg":80},"clouds":{"all":90},"dt":1485789600,"sys":{"type":1,"id":5091,"message":0.0103,"country":"GB","sunrise":1485762037,"sunset":1485794875},"id":2643743,"name":"London","cod":200}
[참고자료] 코딩셰프
- [https://www.youtube.com/watch?v=ccq1yCmNzdk&list=PLQt_pzi-LLfoOpp3b-pnnLXgYpiFEftLB&index=14]
'Flutter > 10 app Weather' 카테고리의 다른 글
[Flutter] App Weather - 5단계 추가 데이터 & 모델링 (0) | 2022.04.29 |
---|---|
[Flutter] App Weather - 4단계 UI (0) | 2022.04.29 |
[Flutter] App Weather - 3.5단계 model of openweathermap (0) | 2022.04.28 |
[Flutter] App Weather - 3단계 json from openweathermap (0) | 2022.04.28 |
[Flutter] App Weather - 1단계 geolocator 8.2.0 (0) | 2022.04.27 |