Creating a professional weather app in Flutter

Creating a professional weather app in Flutter involves several steps, including integrating a weather API, designing a clean and user-friendly UI, and handling data efficiently. Below is a step-by-step guide to building a professional weather app using Flutter:

Step 1: Set Up Your Flutter Project

  1. Create a new Flutter project:

    flutter create weather_app cd weather_app
  2. Add necessary dependencies in your pubspec.yaml file:

    dependencies:flutter:sdk: flutter http: ^0.13.3 flutter_spinkit: ^5.1.0 intl: ^0.17.0 geolocator: ^7.6.2
  3. Run flutter pub get to install the dependencies.

Step 2: Obtain a Weather API Key

  1. Sign up for a weather API like OpenWeatherMap or WeatherAPI.
  2. Get your API key and store it securely.

Step 3: Create the Weather Model

Create a model to parse the JSON data from the API.

classWeather{finalString cityName;final double temperature;finalString mainCondition; Weather({ required this.cityName, required this.temperature, required this.mainCondition,}); factoryWeather.fromJson(Map<String,dynamic> json){returnWeather( cityName: json['name'], temperature: json['main']['temp'].toDouble(), mainCondition: json['weather'][0]['main'],);}}

Step 4: Fetch Weather Data

Create a service to fetch weather data from the API.

import'dart:convert';import'package:http/http.dart'as http;import'package:weather_app/models/weather.dart'; classWeatherService{finalString apiKey ='YOUR_API_KEY_HERE';finalString baseUrl ='https://api.openweathermap.org/data/2.5/weather'; Future<Weather>getWeather(String cityName)async{final response =await http.get(Uri.parse('$baseUrl?q=$cityName&appid=$apiKey&units=metric')); if(response.statusCode ==200){returnWeather.fromJson(jsonDecode(response.body));}else{throwException('Failed to load weather data');}} Future<Weather>getWeatherByLocation(double lat, double lon)async{final response =await http.get(Uri.parse('$baseUrl?lat=$lat&lon=$lon&appid=$apiKey&units=metric')); if(response.statusCode ==200){returnWeather.fromJson(jsonDecode(response.body));}else{throwException('Failed to load weather data');}}}

Step 5: Create the User Interface

Design a clean and professional UI for the app.

import'package:flutter/material.dart';import'package:weather_app/models/weather.dart';import'package:weather_app/services/weather_service.dart';import'package:geolocator/geolocator.dart'; classWeatherScreenextendsStatefulWidget{@override _WeatherScreenState createState()=>_WeatherScreenState();} class _WeatherScreenState extendsState<WeatherScreen>{finalWeatherService _weatherService =WeatherService();Weather? _weather; bool _isLoading =false; @overridevoidinitState(){super.initState();_fetchWeatherByLocation();} Future<void>_fetchWeatherByLocation()async{setState((){ _isLoading =true;}); try{Position position =awaitGeolocator.getCurrentPosition(desiredAccuracy:LocationAccuracy.low); _weather =await _weatherService.getWeatherByLocation(position.latitude, position.longitude);}catch(e){print(e);}finally{setState((){ _isLoading =false;});}} @overrideWidgetbuild(BuildContext context){returnScaffold( appBar:AppBar( title:Text('Weather App'),), body: _isLoading ?Center(child:CircularProgressIndicator()): _weather ==null?Center(child:Text('Failed to load weather data')):Column( mainAxisAlignment:MainAxisAlignment.center, children:[Text( _weather!.cityName, style:TextStyle(fontSize:40, fontWeight:FontWeight.bold),),SizedBox(height:10),Text('${_weather!.temperature.toString()}°C', style:TextStyle(fontSize:30),),SizedBox(height:10),Text( _weather!.mainCondition, style:TextStyle(fontSize:20),),],),);}}

Step 6: Run the App

Replace the main.dart file with the following code:

import'package:flutter/material.dart';import'package:weather_app/screens/weather_screen.dart'; voidmain(){runApp(MyApp());} classMyAppextendsStatelessWidget{@overrideWidgetbuild(BuildContext context){returnMaterialApp( title:'Weather App', theme:ThemeData( primarySwatch:Colors.blue,), home:WeatherScreen(),);}}

Step 7: Test and Deploy

  • Test the app on both Android and iOS devices.
  • Deploy the app to the Google Play Store or Apple App Store.

Additional Enhancements

  1. Add a search bar to allow users to search for weather by city name.
  2. Implement caching to store weather data locally.
  3. Add more details like humidity, wind speed, and weather icons.
  4. Use animations to make the app more engaging.

This guide provides a solid foundation for building a professional weather app in Flutter. You can further customize and enhance the app based on your specific requirements.

Enjoyed this article? Stay informed by joining our newsletter!

Comments

You must be logged in to post a comment.

About Author