Build a Weather App in Flutter with Live API - Complete Tutorial 2025

 

Learn API integration in Flutter! Build a weather app with OpenWeatherMap API. Step-by-step tutorial with JSON parsing, async/await & error handling.



Hey Flutter developers! 👋 Welcome back!

Ready to build something even more exciting? Today we're creating a real Weather App that fetches live data from the internet! This is your first step into working with APIs and real-world data.

Why this matters: Almost every modern app uses APIs - social media, shopping, banking, everything! Master this, and you've unlocked a crucial skill.

🌤️ What We're Building



A beautiful weather app that shows:

  • ✅ Current temperature
  • ✅ Weather condition (Sunny, Rainy, Cloudy)
  • ✅ City name
  • ✅ Humidity & Wind speed
  • ✅ Beautiful weather icons
  • ✅ Live data from OpenWeatherMap API

Time needed: 1 hour
Difficulty: Beginner to Intermediate
Lines of code: ~300 (clean & simple!)


🎯 What You'll Learn

By building this app, you'll master:

This is REAL app development! 🚀


📋 Prerequisites

Before starting:

  • ✅ Flutter installed
  • ✅ Completed my previous tutorials (Todo app knowledge helps!)
  • ✅ Internet connection (for API testing)
  • ✅ 1 hour of focused time

New to Flutter? Check my previous posts first!


🔑 Step 1: Get Your FREE API Key

We'll use OpenWeatherMap - it's free and simple!

Get API Key:

  1. Go to: openweathermap.org/api
  2. Click "Sign Up" (Free!)
  3. Verify your email
  4. Go to "API Keys" section
  5. Copy your API key

Example API Key: a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6

⚠️ Keep it safe! Don't share publicly.


📦 Step 2: Create Project & Add Dependencies

Create Project:

flutter create weather_app
cd weather_app

Add Dependencies:

Open pubspec.yaml and add:

dependencies:
  flutter:
    sdk: flutter
  http: ^1.1.0              # For API calls
  geolocator: ^10.1.0       # For location (optional)

Then run:

flutter pub get

✅ Dependencies installed!


💻 Step 3: The Complete Code




Replace everything in lib/main.dart:

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

void main() {
  runApp(const WeatherApp());
}

class WeatherApp extends StatelessWidget {
  const WeatherApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Weather App',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
        useMaterial3: true,
      ),
      home: const WeatherHomePage(),
    );
  }
}

class WeatherHomePage extends StatefulWidget {
  const WeatherHomePage({Key? key}) : super(key: key);

  @override
  State<WeatherHomePage> createState() => _WeatherHomePageState();
}

class _WeatherHomePageState extends State<WeatherHomePage> {
  // Replace with YOUR API key from OpenWeatherMap
  final String apiKey = 'YOUR_API_KEY_HERE';
  
  // Weather data variables
  String cityName = 'London';
  String temperature = '--';
  String weatherCondition = 'Loading...';
  String weatherIcon = '01d';
  String humidity = '--';
  String windSpeed = '--';
  bool isLoading = false;
  String errorMessage = '';

  // Text controller for city input
  final TextEditingController _cityController = TextEditingController();

  @override
  void initState() {
    super.initState();
    fetchWeather(cityName); // Load London weather on start
  }

  // Fetch weather data from API
  Future<void> fetchWeather(String city) async {
    setState(() {
      isLoading = true;
      errorMessage = '';
    });

    try {
      // API URL
      final url = Uri.parse(
        'https://api.openweathermap.org/data/2.5/weather?q=$city&appid=$apiKey&units=metric'
      );

      // Make API call
      final response = await http.get(url);

      if (response.statusCode == 200) {
        // Success! Parse JSON data
        final data = json.decode(response.body);
        
        setState(() {
          cityName = data['name'];
          temperature = data['main']['temp'].round().toString();
          weatherCondition = data['weather'][0]['main'];
          weatherIcon = data['weather'][0]['icon'];
          humidity = data['main']['humidity'].toString();
          windSpeed = data['wind']['speed'].toString();
          isLoading = false;
        });
      } else if (response.statusCode == 404) {
        // City not found
        setState(() {
          errorMessage = 'City not found! Try another city.';
          isLoading = false;
        });
      } else {
        // Other errors
        setState(() {
          errorMessage = 'Something went wrong. Try again!';
          isLoading = false;
        });
      }
    } catch (e) {
      // Network error
      setState(() {
        errorMessage = 'Check your internet connection!';
        isLoading = false;
      });
    }
  }

  // Get weather icon based on condition
  String getWeatherEmoji(String condition) {
    switch (condition.toLowerCase()) {
      case 'clear':
        return '☀️';
      case 'clouds':
        return '☁️';
      case 'rain':
      case 'drizzle':
        return '🌧️';
      case 'thunderstorm':
        return '⛈️';
      case 'snow':
        return '❄️';
      case 'mist':
      case 'fog':
        return '🌫️';
      default:
        return '🌤️';
    }
  }

  // Show search dialog
  void showSearchDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Search City'),
        content: TextField(
          controller: _cityController,
          decoration: const InputDecoration(
            hintText: 'Enter city name...',
            prefixIcon: Icon(Icons.location_city),
          ),
          onSubmitted: (value) {
            if (value.trim().isNotEmpty) {
              fetchWeather(value.trim());
              Navigator.pop(context);
              _cityController.clear();
            }
          },
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Cancel'),
          ),
          ElevatedButton(
            onPressed: () {
              if (_cityController.text.trim().isNotEmpty) {
                fetchWeather(_cityController.text.trim());
                Navigator.pop(context);
                _cityController.clear();
              }
            },
            child: const Text('Search'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Colors.blue[400]!,
              Colors.blue[800]!,
            ],
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // Top Bar
              Padding(
                padding: const EdgeInsets.all(16.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    const Text(
                      'Weather App',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 24,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    IconButton(
                      onPressed: showSearchDialog,
                      icon: const Icon(Icons.search, color: Colors.white, size: 28),
                    ),
                  ],
                ),
              ),

              // Main Content
              Expanded(
                child: isLoading
                    ? const Center(
                        child: CircularProgressIndicator(color: Colors.white),
                      )
                    : errorMessage.isNotEmpty
                        ? _buildErrorWidget()
                        : _buildWeatherContent(),
              ),
            ],
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => fetchWeather(cityName),
        child: const Icon(Icons.refresh),
      ),
    );
  }

  // Weather content widget
  Widget _buildWeatherContent() {
    return SingleChildScrollView(
      child: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          children: [
            const SizedBox(height: 40),

            // City Name
            Text(
              cityName,
              style: const TextStyle(
                color: Colors.white,
                fontSize: 40,
                fontWeight: FontWeight.w300,
              ),
            ),
            const SizedBox(height: 20),

            // Weather Icon (Emoji)
            Text(
              getWeatherEmoji(weatherCondition),
              style: const TextStyle(fontSize: 120),
            ),
            const SizedBox(height: 20),

            // Temperature
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  temperature,
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 80,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const Text(
                  '°C',
                  style: TextStyle(
                    color: Colors.white70,
                    fontSize: 40,
                    fontWeight: FontWeight.w300,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 10),

            // Weather Condition
            Text(
              weatherCondition,
              style: const TextStyle(
                color: Colors.white70,
                fontSize: 24,
                fontWeight: FontWeight.w300,
              ),
            ),
            const SizedBox(height: 60),

            // Weather Details Card
            Container(
              padding: const EdgeInsets.all(20),
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(0.2),
                borderRadius: BorderRadius.circular(20),
                border: Border.all(
                  color: Colors.white.withOpacity(0.3),
                  width: 1,
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  _buildWeatherDetail('💧', 'Humidity', '$humidity%'),
                  Container(
                    width: 1,
                    height: 60,
                    color: Colors.white.withOpacity(0.3),
                  ),
                  _buildWeatherDetail('💨', 'Wind', '$windSpeed m/s'),
                ],
              ),
            ),
            const SizedBox(height: 40),

            // Tip
            Text(
              'Tap search icon to change city',
              style: TextStyle(
                color: Colors.white.withOpacity(0.7),
                fontSize: 14,
              ),
            ),
          ],
        ),
      ),
    );
  }

  // Weather detail item widget
  Widget _buildWeatherDetail(String emoji, String label, String value) {
    return Column(
      children: [
        Text(
          emoji,
          style: const TextStyle(fontSize: 32),
        ),
        const SizedBox(height: 8),
        Text(
          label,
          style: const TextStyle(
            color: Colors.white70,
            fontSize: 14,
          ),
        ),
        const SizedBox(height: 4),
        Text(
          value,
          style: const TextStyle(
            color: Colors.white,
            fontSize: 20,
            fontWeight: FontWeight.bold,
          ),
        ),
      ],
    );
  }

  // Error widget
  Widget _buildErrorWidget() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.error_outline,
              color: Colors.white,
              size: 80,
            ),
            const SizedBox(height: 20),
            Text(
              errorMessage,
              textAlign: TextAlign.center,
              style: const TextStyle(
                color: Colors.white,
                fontSize: 18,
              ),
            ),
            const SizedBox(height: 30),
            ElevatedButton.icon(
              onPressed: showSearchDialog,
              icon: const Icon(Icons.search),
              label: const Text('Search Again'),
              style: ElevatedButton.styleFrom(
                padding: const EdgeInsets.symmetric(
                  horizontal: 30,
                  vertical: 15,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _cityController.dispose();
    super.dispose();
  }
}

🔧 Step 4: Add Your API Key

IMPORTANT: Replace this line with your actual API key:

final String apiKey = 'YOUR_API_KEY_HERE';

Change to:

final String apiKey = 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6'; // Your real key

🏃 Step 5: Run Your App

flutter run

That's it! Your weather app is live! 🎉


🎨 Understanding the Code

Let me break down the key concepts:

1. API Call Function

Future<void> fetchWeather(String city) async {
  final url = Uri.parse(
    'https://api.openweathermap.org/data/2.5/weather?q=$city&appid=$apiKey&units=metric'
  );
  
  final response = await http.get(url);
  
  if (response.statusCode == 200) {
    final data = json.decode(response.body);
    // Use the data
  }
}

What happens:

  1. Build API URL with city name
  2. Make HTTP GET request
  3. Wait for response (await)
  4. Parse JSON data
  5. Update UI with setState()

2. JSON Parsing

final data = json.decode(response.body);

cityName = data['name'];
temperature = data['main']['temp'].round().toString();
weatherCondition = data['weather'][0]['main'];

API Response looks like:

{
  "name": "London",
  "main": {
    "temp": 15.5,
    "humidity": 80
  },
  "weather": [
    {
      "main": "Clouds",
      "icon": "04d"
    }
  ]
}

3. Async/Await

Future<void> fetchWeather(String city) async {
  final response = await http.get(url);
  // Code waits here until response arrives
}
  • async = This function does asynchronous work
  • await = Wait for this to complete
  • Future<void> = Returns nothing, but takes time

4. Error Handling

try {
  // Try to fetch weather
} catch (e) {
  // Handle errors (no internet, etc.)
  setState(() {
    errorMessage = 'Check your internet!';
  });
}

Handles:

  • No internet connection
  • Invalid city name
  • API errors

✨ Features Breakdown

1. Search Cities

  • Tap search icon
  • Enter any city name
  • Get instant weather data!

2. Live Data

  • Real-time temperature
  • Current weather condition
  • Humidity & wind speed
  • Updates on refresh

3. Beautiful UI

4. Error Handling

  • Invalid city? Shows error
  • No internet? Shows message
  • API error? Handled gracefully

5. Refresh

  • Tap floating button
  • Updates current city
  • Latest weather data




🎯 How API Works




API URL Structure:

https://api.openweathermap.org/data/2.5/weather
  ?q=London           // City name
  &appid=YOUR_KEY     // Your API key
  &units=metric       // Celsius (use 'imperial' for Fahrenheit)

Response Example:

{
  "name": "London",
  "main": {
    "temp": 15.5,
    "humidity": 80,
    "pressure": 1013
  },
  "weather": [{
    "main": "Clouds",
    "description": "broken clouds",
    "icon": "04d"
  }],
  "wind": {
    "speed": 5.5
  }
}

We Extract:

  • name → City name
  • main.temp → Temperature
  • weather[0].main → Condition
  • main.humidity → Humidity %
  • wind.speed → Wind speed

💡 Pro Tips

API Best Practices:

✅ Always use try-catch for API calls
✅ Show loading indicators while fetching
✅ Handle all error cases (404, 500, no internet)
✅ Cache data when possible
✅ Don't expose API keys in production

Performance Tips:

✅ Use const constructors
✅ Dispose controllers properly
✅ Avoid unnecessary rebuilds
✅ Cache weather data locally

User Experience:

✅ Show what's happening (loading, error, success)
✅ Give feedback on every action
✅ Make search easy
✅ Handle edge cases


🐛 Common Issues & Solutions

Issue 1: 401 Unauthorized

Problem: API key invalid or expired

Solution:

// Make sure API key is correct
final String apiKey = 'YOUR_ACTUAL_KEY'; // Check this!

// Wait 10-15 minutes after signup for key activation

Issue 2: City Not Found

Problem: City name misspelled or doesn't exist

Solution:

if (response.statusCode == 404) {
  setState(() {
    errorMessage = 'City not found!';
  });
}

✅ Already handled in our code!

Issue 3: No Internet

Problem: Device offline

Solution:

try {
  // API call
} catch (e) {
  setState(() {
    errorMessage = 'Check internet connection!';
  });
}

✅ Already handled!

Issue 4: Temperature Not Showing

Problem: Trying to access data before it's loaded

Solution:

// Always check if data exists
temperature = data['main']['temp']?.round().toString() ?? '--';

🚀 Enhance Your App

Want to make it even better? Try these:

Easy (10-15 minutes):

  1. Add Fahrenheit Toggle - Switch between °C and °F
  2. Save Last City - Remember user's last search
  3. Add More Details - Pressure, visibility, sunrise/sunset
  4. Dark Mode - Toggle between light/dark themes

Medium (30-45 minutes):

  1. 5-Day Forecast - Show weather for next 5 days
  2. Current Location - Use GPS to get local weather
  3. Multiple Cities - Save favorite cities list
  4. Offline Mode - Cache last fetched data

Advanced (1-2 hours):

  1. Weather Animations - Animated rain, snow, sun
  2. Push Notifications - Alert for weather changes
  3. Widgets - Home screen weather widget
  4. Charts - Temperature graphs

📱 Customize Your App

Change Colors:

decoration: BoxDecoration(
  gradient: LinearGradient(
    colors: [
      Colors.purple[400]!, // Change these!
      Colors.pink[800]!,
    ],
  ),
),

Different Weather Icons:

Instead of emojis, use icon packs:

// Add to pubspec.yaml
weather_icons: ^3.0.0

// Use in code
Icon(WeatherIcons.day_sunny, size: 100)

Add Your Style:

Make it unique - change fonts, colors, animations!


🎓 What You've Learned

Congratulations! You now know:

✅ How to make API calls in Flutter
✅ JSON parsing and data extraction
✅ Async/Await for asynchronous operations
✅ Error handling for network requests
✅ Working with HTTP package
✅ Dynamic UI updates based on API data
✅ Real-world app development patterns

This is HUGE! Most apps use APIs! 🎉


💬 Challenge Time!

Weekend Challenge:

  1. Build this weather app
  2. Add one custom feature (your choice!)
  3. Share screenshot in comments
  4. Best 3 get featured in next post!

Deadline: Sunday
Prize: Feature + shoutout! 🏆


❓ FAQs

Q: Is the API really free?
A: Yes! 60 calls/minute, 1M calls/month free.

Q: Can I use this in production?
A: Yes, but hide API key properly (use environment variables).

Q: What if API is slow?
A: Add timeout and show loading indicator (we already do!).

Q: Can I add more cities?
A: Absolutely! Save them in a list.

Q: How do I get current location weather?
A: Use geolocator package - I'll cover in next post!


🌍 API Alternatives

Don't like OpenWeatherMap? Try these:

All work similarly!


📚 Resources

Learn More:

My Previous Posts:


🎊 Final Thoughts

You just built an app that uses REAL DATA from the internet! 🎉

This is professional-level development!

Remember:

  • APIs power modern apps
  • Error handling is crucial
  • User experience matters
  • Keep learning!

You're becoming a real Flutter developer! 💪


Happy Coding! 🌤️

Vikul Tyagi
Building real-world Flutter apps


Don't forget to:

  • 🔖 Bookmark this guide
  • 📢 Share with learners
  • 💬 Comment your app screenshot
  • ⭐ Try the challenge
  • 🔔 Subscribe for more

Connect: GitHub | LinkedIn 


P.S. - Stuck with API? Comment your error and I'll help! I reply to everyone! 😊

P.P.S. - Next tutorial: Firebase Integration! Get ready! 🔥

Comments

Post a Comment

Popular posts from this blog

10 Flutter Widgets Every Developer Must Know - Complete Guide with Examples 2025

Build a Beautiful Todo App in Flutter - Complete Tutorial 2025