Weather app using API integration in Flutter

Video Tutorial

Creating a New Flutter Project

Fetching the packages

dependencies:
geolocator:
http:

Building the App

import 'package:flutter/material.dart';void main() {
runApp(
MaterialApp(),
);
}
class YourWidgetName extends StatefulWidget {
@override
_YourWidgetNameState createState() => _YourWidgetNameState();
}

class _YourWidgetNameState extends State<YourWidgetName> {
@override
Widget build(BuildContext context) {
return Container();
}
}
import 'package:flutter/material.dart';
import 'homescreen.dart';

void main() {
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
home: HomeScreen(),
theme: ThemeData(
primaryColor: Colors.white,
accentColor: Colors.white,
),
),
);
}

Step 1: Getting Current location co-ordinates

import 'package:geolocator/geolocator.dart';
getCurrentLocation() async {
var p = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.low,
forceAndroidLocationManager: true,
);
if (p != null) {
print('Lat:${p.latitude}, Long:${p.longitude}');

} else {
print('Data unavailable');
}
}
@override
void initState() {
// TODO: implement initState
super.initState();
getCurrentLocation();
}
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(),
);
}

STEP 2: Getting API key from OpenWeatherMap

API call by latitude longitude format
https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API key}
API call by city name format
https://api.openweathermap.org/data/2.5/weather?q={city name}&appid={API key}
const String domain = "https://api.openweathermap.org/data/2.5/weather?";
const String apiKey = "PASTE YOUR API KEY HERE";

STEP 3: Getting weather data of Current location

import 'package:http/http.dart' as http;
import 'constants.dart' as k;
import 'dart:convert';
API call by latitude longitude format
https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API key}
getCurrentCityWeather(Position position) async {
var client = http.Client();
var uri =
'${k.domain}lat=${position.latitude}&lon=${position.longitude}&appid=${k.apiKey}';
var url = Uri.parse(uri);
var response = await client.get(url);
if (response.statusCode == 200) {
var data = response.body;
print(data);
} else {
print(response.statusCode);
}
}

STEP 4: Getting weather data of various cities

API call by city name format
https://api.openweathermap.org/data/2.5/weather?q={city name}&appid={API key}
getCityWeather(String cityname) async {
var client = http.Client();
var uri = '${k.domain}q=$cityname&appid=${k.apiKey}';
var url = Uri.parse(uri);
var response = await client.get(url);
if (response.statusCode == 200) {
var data = response.body;
var decodeData = json.decode(data);
print(data);

} else {
print(response.statusCode);
}
}

STEP 5: Completing the Build

SafeArea(
child: Scaffold(
resizeToAvoidBottomInset: false,
body: Container(
width: double.infinity,
height: double.infinity,
padding: EdgeInsets.all(20),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Color(0xffFA8BFF),
Color(0xff2BD2FF),
Color(0xff2BFF88),
],
begin: Alignment.bottomLeft,
end: Alignment.topRight,
),
),
),
),
);
bool isLoaded = false;
num temp;
num press;
num hum;
num cover;
String cityname = '';
Container(
child: Visibility(
visible: isLoaded,
child: Column(),
replacement: Center(
child: CircularProgressIndicator(),
),
),
),
updateUI(var decodedData) {
setState(() {
if (decodedData == null) {
temp = 0;
press = 0;
hum = 0;
cover = 0;
cityname = 'Not available';
} else {
temp = decodedData['main']['temp'] - 273;
press = decodedData['main']['pressure'];
hum = decodedData['main']['humidity'];
cover = decodedData['clouds']['all'];
cityname = decodedData['name'];
}
});
}
getCurrentCityWeather(Position position) async {
//Networking code
if (response.statusCode == 200) {
var data = response.body;
var decodeData = json.decode(data);
updateUI(decodeData);
setState(() {
isLoaded = true;
});

} else {
print(response.statusCode);
}
}
getCityWeather(String cityname) async {
//Networking code
if (response.statusCode == 200) {
var data = response.body;
var decodeData = json.decode(data);
updateUI(decodeData);
setState(() {
isLoaded = true;
});

} else {
print(response.statusCode);
}
}
TextEditingController controller = TextEditingController();
child: Column(
children: [
Container(
width: MediaQuery.of(context).size.width * 0.85,
height: MediaQuery.of(context).size.height * 0.09,
padding: EdgeInsets.symmetric(
horizontal: 10,
),
decoration: BoxDecoration(
color: Colors.black.withOpacity(0.3),
borderRadius: BorderRadius.all(
Radius.circular(
20,
),
),
),
child: Center(
child: TextFormField(
onFieldSubmitted: (String s) {
setState(() {
cityname = s;
getCityWeather(s);
isLoaded = false;
controller.clear();
});
},
controller: controller,
cursorColor: Colors.white,
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w600,
color: Colors.white),
decoration: InputDecoration(
hintText: 'Search city',
hintStyle: TextStyle(
fontSize: 18,
color: Colors.white.withOpacity(0.7),
fontWeight: FontWeight.w600,
),
prefixIcon: Icon(
Icons.search_rounded,
size: 25,
color: Colors.white.withOpacity(0.7),
),
border: InputBorder.none,
),
),
),
),
],
),
@override
void dispose() {
// TODO: implement dispose
controller.dispose();
super.dispose();
}
SizedBox(
height: 30,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Icon(
Icons.pin_drop,
color: Colors.red,
size: 40,
),
Text(
cityname,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 28,
fontWeight: FontWeight.bold,
),
)
],
),
),
SizedBox(
height: 20,
),
Container(
width: double.infinity,
height: MediaQuery.of(context).size.height * 0.12,
margin: EdgeInsets.symmetric(
vertical: 10,
),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(
Radius.circular(15),
),
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.grey.shade900,
offset: Offset(1, 2),
blurRadius: 3,
spreadRadius: 1,
)
],
),
child: Row(
children: [
Image(
image: AssetImage('images/thermometer.png'),
width: MediaQuery.of(context).size.width * 0.09,
),
SizedBox(
width: 10,
),
Text(
'Temperature: ${temp?.toInt()} ºC',
style: TextStyle(
fontSize: 20, fontWeight: FontWeight.w600),
)
],
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Image(
image: AssetImage('images/barometer.png'),
width: MediaQuery.of(context).size.width * 0.09,
),
),

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ashna Nizam

Ashna Nizam

Electrical engineering student who is a tech enthusiast. Flutter app developer. Reach me in GitHub at https://github.com/AshNiz24