Flutter for Jobseekers

Creating Your First Application

Turning a weather-app design and requirements into a plan, organizing project files, enums and Freezed code generation, and building the API layer.

Creating Your First Application

Throughout this book, we have spent a lot of time discussing the different widgets and concepts that are used to build an application. Now, it is time to put that knowledge to practical use.

In this chapter, you, the reader, will play the role of a Flutter developer, who has just landed their first client. You will be given a design and set of requirements, and it will be up to you to figure out how to best deliver an application to your client.

We are going to use everything we have learned in the book so far to build the application in this chapter. A few new concepts will be introduced as well, such as code generation. This chapter will help guide you through the thought process of converting a design and requirements into an application, but it will be up to you to build it. If you get stuck, though, there will be code in the accompanying repository that you can use as a reference.

Companion code: the publisher's repository holds this chapter's code as Example 12.1–Example 12.10 in the Chapter 12 folder; each code block below is labelled with the first example that contains it. Its Completed Example Application folder holds the whole weather app; a corrected runnable copy is examples/flutter_for_jobseekers_ch12_weather/. The repository has conversion glitches of its own, so the code on this page follows the book (BPB Publications, n.d.).

Chapter overview

Structure

  • About the application (we will be building)
  • Understanding the technical requirements
  • Building the skeleton of your application
  • The WeatherIcon class
  • Code generation
  • Building the API layer
  • Finishing the application

Objectives

In this chapter, you will learn how to take a design and set of requirements and use them to create an application. You will also learn about how to organize your project files, automatically generate code, and use code decorators. Finally, you will have your very first, fully functioning application.

Runnable example

The book does not print the finished app; the publisher's repository ships it, and its corrected runnable copy, with tests that need no network, is examples/flutter_for_jobseekers_ch12_weather/. The chapter's code (the hand-written and Freezed MyClass, the WeatherIcon enum, the API layer) and one widget built with dummy data are available as a runnable project with tests in examples/flutter_for_jobseekers_ch12/. The code on this page is shown as the book prints it, with conversion glitches fixed.
This is, by far, the most challenging chapter of the book. It is also, arguably, the most important. Be sure to take your time with this one, because the concepts you will learn here will be invaluable to you throughout your career!

About the application

The application you will be building throughout this chapter is a weather application. Weather applications are ubiquitous and relatively simple, while offering ample opportunity for creativity in their design. Take a moment to look at a mockup of the main screen of the application in Figure 12.1:

Figure 12.1: The weather application we will be building throughout this chapter

The design for this application leverages a set of free and open-source icons, created by Microsoft. However, you may use any set of icons which suit your tastes. The layout has been created in such a way as to pose a couple of unique challenges to solve.

The Today section

The horizontally scrolling list clearly has padding to the left yet overflows the screen on the right. Were you to scroll all the way to the right, you would see padding on the right with the cards overflowing on the left.

The seven-day forecast

On the seven-day forecast screen (Figure 12.2), the text has been rotated slightly.

Figure 12.2: The 7-day forecast screen mockup

While not particularly difficult challenges to solve, these represent some real-world design challenges you may come across as a Flutter developer. Being able to quickly recognize and reconcile issues such as this is a skill you will need to develop.

The final screen in the application is a very basic Settings screen, where the user can change between Imperial and metric display units (Figure 12.3):

Figure 12.3: The settings screen

While basic, this screen could also be used to add further customizations should you so desire:
  • Perhaps you would like to let the user specify which city to show the weather for.
  • Or, maybe you would like to let the user swap between multiple icon sets,
  • toggle between light and dark mode,
  • adjust the update frequency,
  • or swap between data sources (such as different weather providers).
For now, we will leave this section quite Spartan, but feel free to experiment with it later.

The icons

Let us explore some of the more technical details of the design, starting with the icons. As previously mentioned, these icons are from Microsoft's free and open-source icon set, which was published on GitHub in 2022, making them free for creators to remix and build upon (Tom, 2022). The following is a selection of the emoji which Microsoft has open-sourced (Figure 12.4):

Figure 12.4: A selection of Microsoft's free and open-source Fluent Emoji. Source: GitHub/Microsoft

You can download the full icon set, for free, from Microsoft's GitHub repository: https://github.com/microsoft/fluentui-emoji. From this emoji set, we will be pulling out several icons which specifically apply to weather, including moon phases, weather icons, and a couple of other related icons. The following is a table (Table 12.1) of the images and relevant file names for the specific icons we need:

CategoryIconAsset Name
Weathercloudcloud_3d.png
Weathercloud with lightningcloud_with_lightning_3d.png
Weathercloud with lightning and raincloud_with_lightning_and_rain_3d.png
Weathercloud with raincloud_with_rain_3d.png
Weathercloud with snowcloud_with_snow_3d.png
Weatherfogfog_3d.png
Weatherleaf fluttering in windleaf_fluttering_in_wind_3d.png
Weathersunsun_3d.png
Weathersun behind cloudsun_behind_cloud_3d.png
Weathersun behind large cloudsun_behind_large_cloud_3d.png
Weathersun behind rain cloudsun_behind_rain_cloud_3d.png
Weathersun behind small cloudsun_behind_small_cloud_3d.png
Moonfirst quarter moonfirst_quarter_moon_3d.png
Moonfull moonfull_moon_3d.png
Moonlast quarter moonlast_quarter_moon_3d.png
Moonnew moonnew_moon_3d.png
Moonwaning crescent moonwaning_crescent_moon_3d.png
Moonwaning gibbous moonwaning_gibbous_moon_3d.png
Moonwaxing crescent moonwaxing_crescent_moon_3d.png
Moonwaxing gibbous moonwaxing_gibbous_moon_3d.png
Miscellaneousdropletdroplet_3d.png
Miscellaneouslevel sliderlevel_slider_3d.png
Miscellaneousthermometerthermometer_3d.png
Miscellaneouswind facewind_face_3d.png

Table 12.1: The selection of Fluent Emoji chosen to be used in the example application.

The color palette

Finally, let us explore the color palette that the design calls for. If you are reading the print version of this book, you may find that the colors are quite dark and difficult to differentiate. Once you get to building the application, you may find that the subtle shades of blue are quite pleasing to look at. Let us first start by defining what the colors are (Table 12.2):

Color in RGBColor in Hex
Primaryrgb(15, 4, 76)#0F044C
Secondaryrgb(20, 30, 97)#141E61
Accentrgb(120, 122, 145)#787A91
Textrgb(238, 238, 238)#EEEEEE

Table 12.2: The color palette of our application

Let us try to put these colors into context by seeing where they are applied within our application (Figure 12.5):

Figure 12.5: Applying the color scheme to the design

Runnable copy: examples/flutter_for_jobseekers_ch12/lib/theme.dart (the palette as Color constants)

Now that we understand the visual components of the application, let us look at the technical requirements.

Understanding the technical requirements

At the heart of our application will be data provided by an API. There exist many different weather API providers, each offering slightly different services and levels of detail. Before we can go about choosing a provider, we need to start by identifying the data we will need to consume.

It is also a good idea to look at the pricing that the provider offers. Often, there is a generous free tier, but if you exceed the limit, there will be a cost per API call.
  • Do you plan to use the application only for yourself, or release it to the world?
  • If thousands of people are using your application, how many API calls do you expect each person to use per day?
  • What are the potential costs that you will need to offset?

Costs aside, let us focus on the data we need from an API provider and assume that our usage will fall within their free tier. By examining the design screenshots, we can start to build up an idea of what we need our API provider to give us:

Current weather

Including temperature, conditions, humidity, and wind speed and direction.

Current moon phase

The moon phase right now.

Hourly forecast

Including temperature and conditions.

Seven-day forecast

Including conditions and high/low temperatures.
A nice to have would be the ability to specify a measurement unit to the API so we do not have to do the math to figure out ℃ from ℉ and vice versa; however that is a relatively simple calculation, so it is not wholly necessary.

One weather API provider which meets all the needs outlined preceding, including our nice to have, is Visual Crossing Weather (https://www.visualcrossing.com/). The documentation for Visual Crossing Weather's API can be found at the following location: https://www.visualcrossing.com/resources/documentation/weather-api/timeline-weather-api/.

You will need to register an account to use this service, as only by registering an account will you be able to acquire an API key, which will be sent with every API request to authenticate your request (and track your usage so that you can be billed). Take some time to look over the documentation and see if you can match up the application's requirements with specific parts of the API. The easiest way to do this is by using their query builder (https://www.visualcrossing.com/weather/weather-data-services):

Corrected: the query builder link now redirects to https://www.visualcrossing.com/weather-query-builder/ (checked on 2026-11-16).

Eventually, we will be building Dart classes to handle this output, so understanding it is quite vital.

How the application works

Moving on from the API for now, we need to further understand how our application will be built on a conceptual level. We know, of course, that there will be an API which we have to interact with. We also know that we will be giving the user an option to change the units which are displayed within the application. We can see that there is a set of data displayed on the main screen, with a second set of data being displayed on the seven-day forecast screen. Should all the data be retrieved in the same query? Should there be separate queries? Does it matter? These are all questions we need to be asking ourselves before we start writing code. The answer is up to you, the developer. However, here are some recommendations:

  • We can utilize state management to toggle between different units of measurement.
  • We can use local storage of some sort to save the user's unit of measurement preferences so subsequent app launches will reflect the last-chosen choice.
  • Toggling between units of measurement can trigger a new API call to be performed, using the preferred unit of measurement as a parameter in the call.
  • By using state management to perform our API queries, we can display status updates to the user such as getting location, getting weather, and in the event of a failure, error.
  • Separating the state of the user's preferences from the state of the API calls is probably a good idea.

The final question you will need to answer for yourself (and there is no single, right answer) is how the weather will be fetched/updated after the app has been launched. Will the weather be updated at all? Will there be a pull-to-refresh? Will there be a timer to automatically update the weather on a given interval? (If so, what will the timer interval be? Should it be configurable?) Or will there be a combination of timer and pull-to-refresh?

Building an application from a given design and set of requirements can often be more planning than coding. Without adequate planning, you may end up wasting a significant amount of time by writing code only to realize that your API provider does not quite give you everything you need, requiring you to change providers and redesign all your classes. It could also mean wasting time in developing a state management system that you end up throwing away in favor of a different solution, or something similarly time consuming.As the saying goes: measure twice, cut once. Spending more time understanding the requirements and expectations of an application and planning it all out in the beginning will make building the application itself much, much easier.

Now that we have a firm understanding of both the design and technical requirements of the application which we will be building, let us dive into the actual process of building the application itself.

Building the skeleton of your application

As with every new Flutter project, we can use flutter create weather to create a new application. This will leave us with a main.dart that includes the standard counter application, which we can remove and replace with our own widgets. There are several components to our application which will need to be organized effectively.

Up to this point, we have not discussed how to keep files organized in a project, but having an organized codebase is vital. There are no rules to define how your code should be organized, and if you are joining an established team with an existing codebase, try to understand and utilize their organization structure before making up your own. However, if you are starting from scratch, you will not have anything existing to adapt to. In that case, here is a suggestion for keeping your code organized:

📁 lib/
├ 📁 common/
│ ├ 📄 theme.dart
│ ├ 📁 classes/     Common data classes used throughout the application
│ └ 📁 widgets/     Widget(s) which are used in multiple features
├ 📁 features/
│ └ 📁 my_feature/
│   ├ 📁 api/              Feature-specific API files
│   ├ 📁 state (or bloc)/  Files related to state management
│   ├ 📁 classes/          Any data class(es) specific to the given feature
│   ├ 📁 screens/          The screen(s) related to your feature
│   │ └ 📄 feature_screen.dart
│   └ 📁 widgets/          Widget(s) which are specific to your feature
└ 📄 main.dart
If your application is simple, it is okay to forego the common and features directories, instead bringing their contents up a level to the lib directory. Either way, this is only a suggestion, and you may find a method which makes more sense to you.

Building with dummy data

When building out a new application or feature, often the easiest way is to use dummy data to get the layout right before ever making an API call. So, what does that mean and how does it look, in practice?

Let us say you are building the widget on the home screen which displays the current weather conditions (the large icon with temperature and conditions beneath it). Building that widget will require three pieces of information: the icon we need to display, the temperature, and the description of the current conditions. By taking those three parameters into the widget, we can temporarily pass in whatever data we want without making an API call.

Values passed in

The widget does not care where the values come from, only that they exist. When you eventually build out the portion of the application which supplies data from the API, you can easily swap the parameters used to build the widget from your dummy data to the live data. You are also easily able to test out different scenarios for wrong or missing data, which will help you build a more robust widget.

Values fetched by the widget

If we opted not to pass any values into the widget and instead asked the widget to retrieve its values from our state management system, it would make the widget far more difficult to develop and test.

Runnable copy (assembled, not in the book): examples/flutter_for_jobseekers_ch12/lib/current_conditions.dart (the CurrentConditions widget) and lib/main.dart (fed with dummy data: tap a chip to switch the icon)

A keen-eyed reader may have noticed that one such parameter being supplied to this widget is of the class WeatherIcon. Let us spend some time looking over this class, how it was constructed, and what is unique about it.

The WeatherIcon class

The Visual Crossing Weather API helpfully returns a weather icon identifier that we can use in our application. Let us start by exploring the documentation for this portion of the API: https://www.visualcrossing.com/resources/documentation/weather-api/defining-icon-set-in-the-weather-api/.

According to the documentation, there are two possible icon sets we can use in the application. The first icon set includes nine possibilities, while the second set includes 16. The documentation also gives us the possible icon identifiers which will be returned from the API and a description of when those icons will be used in relationship to the weather. We can use these icon IDs to map to image assets we include within our application. But, how? To explain this, we first need to discuss enums and generated code.

Enums

Enumerated types (for short, enumerations, or most commonly, simply enums) are a Dart type which extends the Enum class. An enum represents a fixed list of constants. Take this simple enum example: enum Answers { yes, no, maybe } wherein the list of possible answers can only ever be yes, no, or maybe. Referencing a value from the enum would work like this: Answers.yes.

Enums are quite powerful in that all possible conditions are guaranteed. When building a widget that has a different state for a given set of enums, you can be guaranteed that the possible conditions in an enum will not change.

Enums are extremely powerful, but also quite limited. Since they only represent a constant list of options and nothing more, we have no way to assign values to the items within an enum. Or…do we?

In fact, we do. Dart offers enhanced enums, which allows us to extend the functionality beyond the base functionality provided. For example, we can create a getter which associates a value with an enum value:

Example 12.1 · Example 12.1.dart
enum Answers {
  yes("Happy"),
  no("Sad"),
  maybe("confused");

  final String feeling;

  const Answers(this.feeling);
}

Here, we are mapping a feeling string to an answer. To get the feeling, we can simply call Answers.yes.feeling which would return Happy. Since we can use methods to return a value, we can create all sorts of complex getters or, really, do anything we want. When we create our WeatherIcon enum, we can map a specific value to the location of an image asset included within our application. Before we get to that, however, we need to talk about code generation.

Corrected: strictly, feeling here is a final instance field set by a const constructor, not a getter; reading it looks the same (Answers.yes.feeling). Enhanced enums can declare fields, constructors, methods and getters, and arrived in Dart 2.17 (Dart, n.d.-b).

Code generation

When we are building classes for our application, especially when we expect to instantiate an instance of that class using JSON data from an API, we need to define a factory constructor which will take in the JSON data and convert it into an instance of our class. We might also want to create a method which converts the class to a JSON object, in case we want to send it to an API as a value. Doing this by hand requires us to maintain a careful mapping of each possible value, how it maps to our class, and necessitates us considering whether that value can be null. With a single parameter, this is what building such a class might look like:

Example 12.2 · Example 12.2.dart
class MyClass {
  final String value;

  const MyClass({required this.value});

  factory MyClass.fromJson(Map<String, dynamic> json) {
    return MyClass(
      value: json["value"],
    );
  }

  @override
  int get hashCode {
    return Object.hash(
      runtimeType,
      value,
    );
  }

  @override
  bool operator ==(Object other) {
    return other is MyClass &&
    other.runtimeType == runtimeType &&
    other.value == value;
  }

  MyClass copyWith({
      required String value,
  }) {
    return MyClass(
      value: value,
    );
  }

  Map<String, dynamic> toJson(MyClass myClass) {
    return <String, dynamic>{
      "value": myClass.value,
    };
  }

  @override
  String toString() {
    return 'MyClass('
      'value: $value'
      ')';
  }
}
Corrected: two methods do not do what their names promise. copyWith with a required parameter is just a second constructor; it should take an optional String? value and fall back to this.value. toJson should take no argument and read the instance's own fields, which is the shape jsonEncode calls (the book's version takes another MyClass).Runnable copy:examples/flutter_for_jobseekers_ch12/lib/my_class_manual.dart (with both fixes)

That is a whole lot of code just for a single value! Plus, the object we can create from this class lacks a whole lot of other, useful features. Creating all these methods for every class we create is needlessly time-consuming, error-prone, and not very fun. Would it not be nice if we could let Dart write all that code for us?

Freezed

The freezed package, by the indomitable Remi Rousselet (@rrousselGit on GitHub), allows us to accomplish just such a task. Freezed is an extremely powerful and popular package with many features, all of which are geared toward the task of automatically generating code. To get started with Freezed, first enable it in the command line:

flutter pub add freezed_annotation
flutter pub add --dev build_runner
flutter pub add --dev freezed
# if using freezed to generate fromJson/toJson, also add:
flutter pub add json_annotation
flutter pub add --dev json_serializable

Then, we can rewrite our class using a decorator. You have seen a decorator before, even if you did not realize or understand it at the time. Both the @immutable and @override lines are decorators, for example.

Corrected: Dart calls these metadata annotations: "A metadata annotation begins with the character @", and you "use metadata to provide additional static information about your code" (Dart, n.d.-a). An annotation does not change the code by itself; tools such as the analyzer or a code generator read it. The decorator pattern in Further reading is a different idea: an object that wraps another object to add behavior.

Here is the exact same class we created by hand, but this time we are getting ready to use code generation:

Example 12.3 · Example 12.3.dart
@freezed
class MyClass with _$MyClass {
  const factory MyClass({
      required String value,
  }) = _MyClass;

  factory MyClass.fromJson(Map<String, dynamic> json) =>
  _$MyClassFromJson(json);
}

Of course, we will still need to generate our code (then regenerate it each time we change the class definition), but that is a small price to pay. We will also need to import the generated file. A complete example would look like the following:

Example 12.3 · Example 12.3.dart
import 'package:freezed_annotation/freezed_annotation.dart';

part 'my_class.freezed.dart';
part 'my_class.g.dart';

@freezed
class MyClass with _$MyClass {
  const factory MyClass({
      required String value,
  }) = _MyClass;

  factory MyClass.fromJson(Map<String, dynamic> json) =>
  _$MyClassFromJson(json);
}
Corrected: Freezed 3's migration guide says "Classes using the factory constructor now require a keyword sealed / abstract", so the declaration is abstract class MyClass with _$MyClass (Rousselet, n.d.).Runnable copy:examples/flutter_for_jobseekers_ch12/lib/my_class.dart (with the generated my_class.freezed.dart and my_class.g.dart; a test checks that it behaves like the hand-written class)

Then, to generate the file, we would run (from the root of our project) the following command:

dart run build_runner build --delete-conflicting-outputs

Once build_runner has finished, our code will have been generated and we can use it as normal.

Mapping the API's icon IDs

So, how does this relate to our WeatherIcon enum and why do we even need code generation in the first place? Let us start by taking another look at the possible icon identifiers that icon set 2 can return from the API:

Snow

  • snow
  • snow-showers-day
  • snow-showers-night

Thunder

  • thunder-rain
  • thunder-showers-day
  • thunder-showers-night

Rain

  • rain
  • showers-day
  • showers-night

Fog, wind, clouds, clear

  • fog
  • wind
  • cloudy
  • partly-cloudy-day
  • partly-cloudy-night
  • clear-day
  • clear-night

Some of the possible IDs have a hyphen in them. Dart does not like hyphens in the names of things. Creating an enum for the weather IDs as-is would cause Dart to complain endlessly about those items with hyphens. Stringing together words with hyphens is called kebab case. Dart prefers to use Pascal case for class names and camel case for other types of names. What is the difference, you ask? This ought to give you an idea:

  • camelCase
  • PascalCase
  • snake_case
  • kebab-case
Corrected: a hyphen is not a style issue but a syntax error: an identifier can only contain letters, digits, _ and $, so clear-day is read as clear - day. The Effective Dart names for the two styles are UpperCamelCase (Pascal case: "DO name types using UpperCamelCase") and lowerCamelCase (Dart, n.d.-c).

So, if we create an enum with items that exactly matches the values the API will return, Dart will get upset. Yet, we cannot change the values coming from the API. So, how do we map the kebab case variables to our camel case enum? This is where Freezed comes into play. Specifically, the freezed_annotation package, which is itself useless without Freezed.

This package will tell Freezed that a given value should be mapped to another value. This could be in a class definition when defining a property or in an enum, such as in our case. We use this by using a @JsonValue decorator on the property in question. Let us apply this to an enum to see how it works:

Example 12.4 · Example 12.4.dart
import 'package:freezed_annotation/freezed_annotation.dart';

enum WeatherIcon {
  @JsonValue('clear-day')
  clearDay,
  @JsonValue('clear-night')
  clearNight,
  cloudy,
  fog,
  @JsonValue('partly-cloudy-day')
  partlyCloudyDay,
  @JsonValue('partly-cloudy-night')
  partlyCloudyNight,
  rain,
  @JsonValue('showers-day')
  showersDay,
  @JsonValue('showers-night')
  showersNight,
  snow,
  @JsonValue('snow-showers-day')
  snowShowersDay,
  @JsonValue('snow-showers-night')
  snowShowersNight,
  @JsonValue('thunder-rain')
  thunderRain,
  @JsonValue('thunder-showers-day')
  thunderShowersDay,
  @JsonValue('thunder-showers-night')
  thunderShowersNight,
  wind,
}
Corrected:@JsonValue comes from the json_annotation package (which freezed_annotation re-exports), and it is read by json_serializable, not by Freezed: Freezed only marks the class it generates with @JsonSerializable, and json_serializable writes _$MyClassFromJson into *.g.dart. The mapping is used when a class with a WeatherIcon field is decoded, as in the example's Conditions class.

Now, when we map the JSON output of the API to our enum, those pesky kebab case names will map nicely to our camel case names! Feel free to complete this by creating a getter which maps the image asset to the relevant enum. You may wish to map the enums to these strings:

Example 12.5 · Example 12.5.dart
WeatherIcon.clearDay: 'assets/images/weather/sun_3d.png',
WeatherIcon.clearNight: 'assets/images/moon/full_moon_3d.png',
WeatherIcon.cloudy: 'assets/images/weather/cloud_3d.png',
WeatherIcon.fog: 'assets/images/weather/fog_3d.png',
WeatherIcon.partlyCloudyDay: 'assets/images/weather/sun_behind_small_cloud_3d.png',
WeatherIcon.partlyCloudyNight: 'assets/images/weather/sun_behind_small_cloud_3d.png',
WeatherIcon.rain: 'assets/images/weather/cloud_with_rain_3d.png',
WeatherIcon.showersDay: 'assets/images/weather/sun_behind_rain_cloud_3d.png',
WeatherIcon.showersNight: 'assets/images/weather/sun_behind_rain_cloud_3d.png',
WeatherIcon.snow: 'assets/images/weather/cloud_with_snow_3d.png',
WeatherIcon.snowShowersDay: 'assets/images/weather/cloud_with_snow_3d.png',
WeatherIcon.snowShowersNight: 'assets/images/weather/cloud_with_snow_3d.png',
WeatherIcon.thunderRain: 'assets/images/weather/cloud_with_lightning_and_rain_3d.png',
WeatherIcon.thunderShowersDay: 'assets/images/weather/cloud_with_lightning_3d.png',
WeatherIcon.thunderShowersNight: 'assets/images/weather/cloud_with_lightning_3d.png',
WeatherIcon.wind: 'assets/images/weather/leaf_fluttering_in_wind_3d.png',

Companion code: Example 12.5 does not use a map: it stores each asset path in the enum itself, as an enhanced enum with an image field.

Runnable copy: examples/flutter_for_jobseekers_ch12/lib/weather_icon.dart (with an asset getter built from this map; tests check all 16 @JsonValue mappings and that every asset file exists)

Now that you have created your WeatherIcon enum, you can use it to display an image in your layout. Go back to your CurrentConditions widget and plug in a value from your enum to see the image!

Code generation is an incredibly powerful tool which will save you countless hours of typing and tediously debugging code. Do not be afraid to use it often!

Building the API layer

Our weather application will need to communicate with the Visual Crossing Weather API to get the current conditions and forecast. We previously discussed communicating with APIs in Chapter 7, Working with APIs and Asynchronous Operations. Now, we are going to expand upon the knowledge from that chapter to create our own WeatherApi class.

The idea behind our WeatherApi will be that we can create an instance of it and ask it to get the weather for us, like this: WeatherApi().getWeather. Any time we need to fetch the weather, we can call the same method. We expect that this call will return a CurrentWeather class, containing all the data we need from the API to build the widgets in our application. That means that our WeatherApi will do some sanity checking and error handling before returning a value to us.

Error checking

There are several different ways to do error checking. It is possible to use a try-catch to account for errors. However, this can sometimes make debugging difficult. A try-catch would look something like the following:

Example 12.6 · Example 12.6.dart
try {
  final Response response = await http.get('https://my-api');
  final CurrentWeather weather = CurrentWeather.fromJson(response.data);
  return weather;
} catch (e) {
  throw Exception(e);
}
The downside of using a try-catch here is that we do not know what broke. Was there an HTTP error in fetching the response from the API? Was there a problem with the returned data and we could not build a CurrentWeather object from it? We just don't know. In some scenarios, a try-catch is useful, but it could be argued in this case that it is not.

Let us try a different method, instead:

Example 12.7 · Example 12.7.dart
final Response response = await http.get('https://my-api');
CurrentWeather? weather;
if (response.statusCode == 200 && response.data != null) {
  weather = CurrentWeather.fromJson(response.data);
}
return weather;

In this method, we first create a variable of type CurrentWeather, which is nullable (and null). Then, we check to see if our response had a successful status code (in this case, HTTP 200) and that there is data in the body of the response. If those checks pass, we build the new CurrentWeather class using that data. If we wanted to, we could also verify the object that we build is a valid object before returning it.

Corrected: both snippets mix two HTTP clients. http.get from the http package takes a Uri, not a String, and its Response has body (a String), not data. The prose below picks Dio, whose get takes a String and whose Response.data holds the decoded JSON, so with Dio the call is dio.get(...). Dio also throws a DioException for any status outside 200–299 by default (its default validateStatus), so the statusCode == 200 check above never sees an error status unless you pass validateStatus: (_) => true; a test in the example shows both cases.

What the API needs

Let us take this knowledge and finish building out the rest of the API. We are going to need a few different things to do this properly:

An HTTP client

Which one you choose to use is up to you. In this example, we will be using Dio.

The URL

What URL to send our queries to. This can be found in the Visual Crossing Weather API documentation but will also be listed in the following code.

The user's location

We will also need the user's location.

The API key and options

The API key to authenticate our requests to the API, and some options to send along to the API.

The API key

Let us first look at the API key. An API key is a string of text which uniquely identifies you to the API, much like a username and password. Often, this key will be included in the URL, although sometimes it can end up in the request headers, which are options passed along to the API but are not explicitly defined in the URL.

What is important is that this token acts like credentials and should be stored safely and securely, and not checked into source control. One way we can safely store your API key and other secrets is to use an environment variable.

Environment variables are variables that are unique to the environment the code is being run on. That could be a variable set in the command line before running the application or a variable loaded from a file that does not get checked into source control. We will be using the second method.

To get started, we need to create something called a dotfile. In Linux and macOS, unlike in Windows, files which begin with a period in the filename are considered hidden files — they are dotfiles. We are going to create a dotfile in the top-most level of our project, in the directory where you would find the lib folder. Name this file .env and then create a .gitignore file if it does not already exist, then add the following lines to it:

.gitignore
# Environment Variables and Secrets
.env
*.env
**/.env

This will ensure that any environment variables saved in a dotfile with a filename of .env, located anywhere in your project, are not checked into source control, preventing your secrets from being leaked. Next, open the .env file and add a line like this:

.env
API_KEY = "my-api-token"

You can find the key to put in here by logging into your account at https://www.visualcrossing.com/account and then looking for the key section. Once your secret is set, head over to Pub and learn how to activate the flutter_dotenv package for your project. Next, head over to your main.dart and make the following change:

Example 12.8 · Example 12.8.dart
Future<void> main() async {
  await dotenv.load(fileName: ".env");
  runApp(const MyApp());
}

Finally, you can load up the variable in your API class like the following:

Example 12.8 · Example 12.8.dart
final String? apiKey = dotenv.env['API_KEY'];
Corrected: this keeps the key out of source control, but not out of the app. flutter_dotenv loads .env as an asset, so you must list it under flutter: assets: in pubspec.yaml, and it is then bundled into the build. The package's README says: "Do not store secrets (API keys, tokens, passwords) in your .env file. Flutter assets are bundled into the app binary and can be extracted by anyone with access to the build", and "Values loaded by this package should be treated as public client-side configuration" (flutter_dotenv, n.d.). For a published app, keep the real key on a server you control and let the app call that server.

The user's location

Now that your secrets are safe, let us get the user's location. We can use the location package to easily get the user's location; however, there is a bit of extra setup work, so be sure to read and follow the documentation. Once you have got the package set up properly, you can get the location like the following:

Example 12.9 · Example 12.9.dart
final LocationData location = await getLocation();
final double? lat = location.latitude;
final double? lon = location.longitude;
Corrected: the location package has no top-level getLocation() function. getLocation() is a method of a Location instance: final LocationData location = await Location().getLocation();. The README creates Location location = Location(); and calls await location.getLocation(); after checking that the service is enabled and permission is granted (location, n.d.).

The request URL

If we cannot acquire the user's location, we will want to throw some sort of an error, so be sure to check for that. Otherwise, we have everything we need to craft the URL for our request. Again, be sure to reference the API documentation for exactly how to do this. What you will see in the following should work, however, you will need to understand what is being requested and why before you go about implementing it.

Example 12.10 · Example 12.10.dart
const String baseUrl = 'https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services';
final Response response = await http.get('$baseUrl/timeline/$lat,$lon?unitGroup=$unit&include=hours%2Ccurrent&key=$apiKey&contentType=json');

Also note that we pass in a variable for the units. This could either be us or metric. If you recall, the designs had a preferences screen where the user can toggle between these units. Whatever way you decide to implement the preferences, you will want to read that variable from the user's preferences.

Corrected: (checked against Visual Crossing's documentation on 2026-11-16)
  • The URL does not ask for icon set 2. "If you do not include the iconSet parameter, the Timeline Weather API uses icons1", whose 9 IDs leave seven WeatherIcon values unused; add &iconSet=icons2 (Visual Crossing, n.d.-a).
  • The seven-day forecast is daily data. The documentation lists days, hours and current as separate include sections and does not say whether include=hours,current still returns the days, so the example asks for all three: include=days%2Chours%2Ccurrent. Without dates, the Timeline API returns "the forecast at the requested location for the next 15 days" (Visual Crossing, n.d.-b).
  • unitGroup also accepts uk and base besides us and metric; us is the default (Visual Crossing, n.d.-b).
  • As in the error-checking snippets, with Dio the call is dio.get(...).
Runnable copy (assembled from the fragments above):examples/flutter_for_jobseekers_ch12/lib/weather_api.dart and lib/current_weather.dart. Location, API key and unit are parameters, so the class runs without the location and flutter_dotenv setup, and the tests answer its requests with a fake Dio adapter instead of the network.

Finishing the application

The most challenging parts of the application are out of the way; the rest will be up to you to build. Have some fun with it! The important thing to keep in mind is that you are still learning, and this is the first time you have been asked to build something from scratch. You will make mistakes. That is just part of the learning process.

Try on your own first

If you get really stuck, feel free to reference the code at the end of this chapter, but try to figure things out on your own before resorting to doing so.

Companion code: that code is not printed in the book; it is the repository's Completed Example Application folder. Its corrected runnable copy is examples/flutter_for_jobseekers_ch12_weather/; the copy's README.md lists every difference from the repository.

Revisit the earlier chapters

If you get stuck on a particular subject, be sure to check out the previous chapters in this book, as the application was designed in such a way as to take advantage of the knowledge presented throughout this book, with the only new knowledge needed to build the application having been presented in this chapter.

Search online

If you find that nothing else has worked, you may wish to start searching online for answers. The website Stack Overflow (https://stackoverflow.com/) is not only an excellent resource for asking questions and discovering whether your question has already been answered, but also has a reputation on the internet for being the only way programmers learn to write code (Figure 12.6).

Figure 12.6: A running joke in the industry. Original artwork by Edwin Hoffman.

When you finish building your application, be sure to post screenshots online to gather feedback and showcase your hard work! Sharing the fruits of your labor is one of the most rewarding parts of software development. Plus, your friends and family will be awestruck by what you have accomplished!

Conclusion

Building your first application is no small thing. Even an application as simple as our weather application can be quite complex with a lot of challenges to solve. As you begin working in the industry, whether you are taking on clients or working for another company, you will end up applying many concepts from this chapter in your daily work. Being able to take a design and break down the technical requirements from it, plan out the work, and effectively organize your code will be a recurring theme for you. While it is easy to get carried away and just start writing code without any forethought or planning, doing so will only cause you frustration in the long run.

Without a doubt, this was the hardest chapter in the entire book. A lot was asked of you here, and by making it this far, you deserve to feel proud of what you have accomplished! In the upcoming chapter, we are going to deep dive into finding a job as a Flutter developer. Not only will we learn how to hack the system and make the jobs come to us, but we will get direct insights from several of the top Flutter recruiters. This is exciting stuff that you will not want to miss.

Questions

  1. What does open-source mean? What are some different open-source licenses?
  2. What are some factors to consider when selecting a data provider, such as a third-party API?
  3. Why is it important to keep your code organized? What are some ways you can organize it?
  4. What is an enum?
  5. What is a decorator?
  6. What is code generation?
  7. What package can be used to generate code?
  8. What case style does Dart prefer for class names? For variable names?
  9. How can you keep secrets, such as an API key, safe?
  10. What are some good resources for finding answers to programming questions?

Key terms

Dotfile
A file with a filename prefixed with a period. In Linux and macOS, dotfiles are hidden files.
Enum
Enumerated types, or enumerations, are a Dart type which represents a fixed list of constants.
Hex
Short for hexadecimal; a base-16 method of representing numbers. Numbers in hexadecimal range from 0-9 and A-F, with A being equivalent to 11.Corrected: A is equivalent to 10 (and F to 15).
Mockup
A non-functioning representation of an application, often provided by an app designer, that depicts the desired look and feel of an application.
Open-source
Resources, often code, which are freely available to examine, use, and change. There exist many open-source licenses, such as GPL, BSD, and CC. Understanding the limitations and privileges of each is vital to not being sued for improper usage.
RGB
Standing for Red, Green, and Blue, this is a numerical way to represent colors. Each color channel can be represented as a value from 0 (there is none of that color) to 255 (that color is at full intensity).

Command reference

flutter run build_runner build --delete-conflicting-outputs
(Re-)generates code using build_runner.Corrected: the command is dart run build_runner build --delete-conflicting-outputs, as in Code generation above; flutter run starts an app and does not run package executables.

Further reading

Case styles

Read more about case styles: camel, Pascal, snake and kebab case.

Decorator pattern

For more information about decorators, it is worth looking over the Wikipedia page which describes the decorator pattern.

References

Copyright © 2026