Build a Realtime weather app in Flutter — using FutureBuilder

Samia Ashraf
Flutter Community
Published in
5 min readJul 24, 2022

--

In this article, we will explore FutureBuilder to build a weather app from realtime data using OpenWeatherMap API that displays weather data for user’s current location as well as any other location. We will also explore how FutureBuilder lets the widget enter different states during the API call.

I will breakdown the different steps to get realtime data from OpenWeatherMap API and display in our app using FutureBuilder.

The steps include:

  1. get the apiKey
  2. building a simple UI using Stateful widget and FutureBuilder— although you can have full control here and build your own UI
  3. http — to make http request to the api
  4. Get user’s current location(latitude, longitude) using geolocator package and geocoding package to get the current city of the user
  5. Using FutureBuilder to call the api asynchronously
  6. anim_search_bar to call api with different city names and to add some animation to our app

Following is the File Structure of the project:

— api_key.dart : consists of the API key from the OpenWeatherMap api registration.

— constants.dart : this file consists of TextStyle constants

models folder consists of the weather_model

— call_to_api.dart : this file has the code for the call to api

— weather_page.dart : this file consists of the code for the UI of the project

file structure

1. Get the apiKey:

Register with your email in OpenWeatherMap. Then you will have access to the API key here. You will not have access to the weather data without the API key.

Once you get the API key, store it in api_key.dart,

2. Building simple UI with Stateful widget

I have kept the UI very simple with the text widgets representing the data from the API and some background colour gradient to add some interesting element to the screen.

The UI makes use of FutureBuilder widget,

The above design code yields the following UI,

3. http — to make http request to the api

Uri class helps to encode and decode different parts of URI(Uniform Resource Identifier) such as the host, scheme, port and so on.

I have used the https scheme with URI, and therefore have used Uri.https() constructor. The final url looks like this —

https://api.openweathermap.org/data/2.5/weather?q=Dubai&units=metric&appid='your api key'

Using the get request from the http package, we will call the api. The response from the api is stored in Response object, and then the response body is decoded.

The data from api will be converted into WeatherModel object using the WeatherModel.fromMap() method to use later in the view.

WeatherModel stores the current temperature, city name and the weather description.

The API call must be enclosed within a try catch block in order to handle errors, either from the API or the user’s device.

In case the API returns error, the control will enter the catch block and return the error with a message.

4. geolocator package and geocoding package to get the current location of the user

If currentCity is true, then user’s current city is obtained using getCurrentPosition(). The getCurrentPosition() function returns a Position object which contains user’s current position details, including latitude and longitude. Using these values and geocoding package, the user’s current city is obtained and then assigned to the cityName parameter which then calls the api.

var url = Uri.https(‘api.openweathermap.org’, ‘/data/2.5/weather’,{‘q’: cityName, “units”: “metric”, “appid”: apiKey});

5. Using FutureBuilder to call the api asynchronously

FutureBuilder is a widget which lets you determine the current state of a Future and choose what to show during that state.

When the widget first builds, initState() function calls getData() function which calls the API to get the data.

getData(bool isCurrentCity, String cityName) 

isCurrentCity — true if api is called using the user’s current city, false when api is called using search text

cityName — “”(empty string) when location is obtained using geolocator package, otherwise, search text is passed

The function returns WeatherModel.

The FutureBuilder handles the different states of the app during the api call where it runs into one of the three states:

  • waiting state
  • connection done state
  • error state

Waiting state

Before calling the api, there will be no data because Future is busy fetching data, so the waiting state is entered. The user will know this when you return CircularProgressIndicatior() indicating that the api call is not complete and that the data is still being fetched.

Connection done state

Once the data is fetched, Future returns data, it is then checked for errors. If error is encountered then appropriate message is displayed. For example, if the city name is incorrect, then it enters snapshot.hasError and displays the error message in UI.

If there are no errors, then UI is rebuilt with the data from the API.

6. anim_search_bar to call api with different city names and to add some animation to the app

Not only can you search for current location weather data, but you can also search for weather data based on city name.

I have used a package anim_search_bar to add a search bar that reads the city name and then calls the api when done.

Once the api is called with search text city name, the Future returns a new WeatherModel and the widget rebuilds with the latest snapshot of Future.

I hope you got a basic idea of what FutureBuilders are how it can help you to build apps. It is comparatively easier as it handles various states during api call. Read the docs to find more information on FutureBuilder.

You can find the full code on https://github.com/SamiaAshraff/WeatherCast

Feel free to leave a comment and share as much if you found it helpful!

Follow Flutter Community on Twitter: https://www.twitter.com/FlutterComm

--

--

Samia Ashraf
Flutter Community

Flutter enthusiast | Google Developer Expert - Flutter & Dart | Co-organizer @uae_flutter | Ambassador @WomenTechmakers