Last active
May 31, 2019 16:12
-
-
Save timbergus/98af0d2277035c157e746166c0d4222d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:convert'; | |
import 'package:flutter/material.dart'; | |
import 'package:geolocator/geolocator.dart'; | |
import 'package:http/http.dart' as http; | |
void main() => runApp(MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'My Weather App', | |
home: MyHomePage(), | |
); | |
} | |
} | |
class MyHomePage extends StatefulWidget { | |
@override | |
_MyHomePageState createState() => _MyHomePageState(); | |
} | |
class _MyHomePageState extends State<MyHomePage> { | |
String _locality = ''; | |
String _weather = ''; | |
Future<Position> getPosition() async { | |
Position position = await Geolocator() | |
.getCurrentPosition(desiredAccuracy: LocationAccuracy.high); | |
return position; | |
} | |
Future<Placemark> getPlacemark(double latitude, double longitude) async { | |
List<Placemark> placemark = await Geolocator() | |
.placemarkFromCoordinates(latitude, longitude); | |
return placemark[0]; | |
} | |
Future<String> getData(double latitude, double longitude) async { | |
String api = 'http://api.openweathermap.org/data/2.5/forecast'; | |
String appId = '<YOUR_OWN_API_KEY>'; | |
String url = '$api?lat=$latitude&lon=$longitude&APPID=$appId'; | |
http.Response response = await http.get(url); | |
Map parsed = json.decode(response.body); | |
return parsed['list'][0]['weather'][0]['description']; | |
} | |
@override | |
void initState() { | |
super.initState(); | |
getPosition().then((position) { | |
getPlacemark(position.latitude, position.longitude).then((data) { | |
getData(position.latitude, position.longitude).then((weather) { | |
setState(() { | |
_locality = data.locality; | |
_weather = weather; | |
}); | |
}); | |
}); | |
}); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text('My Weather App'), | |
), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: <Widget>[ | |
Text( | |
'$_locality', | |
style: Theme.of(context).textTheme.display1, | |
), | |
Text( | |
'$_weather', | |
style: Theme.of(context).textTheme.display1, | |
), | |
], | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment