Creating Your First Application
Creating Your First Application
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.
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
Runnable example
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.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 seven-day forecast

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
- 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).
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:
| Category | Icon | Asset Name |
|---|---|---|
| Weather | cloud_3d.png | |
| Weather | cloud_with_lightning_3d.png | |
| Weather | cloud_with_lightning_and_rain_3d.png | |
| Weather | cloud_with_rain_3d.png | |
| Weather | cloud_with_snow_3d.png | |
| Weather | fog_3d.png | |
| Weather | leaf_fluttering_in_wind_3d.png | |
| Weather | sun_3d.png | |
| Weather | sun_behind_cloud_3d.png | |
| Weather | sun_behind_large_cloud_3d.png | |
| Weather | sun_behind_rain_cloud_3d.png | |
| Weather | sun_behind_small_cloud_3d.png | |
| Moon | first_quarter_moon_3d.png | |
| Moon | full_moon_3d.png | |
| Moon | last_quarter_moon_3d.png | |
| Moon | new_moon_3d.png | |
| Moon | waning_crescent_moon_3d.png | |
| Moon | waning_gibbous_moon_3d.png | |
| Moon | waxing_crescent_moon_3d.png | |
| Moon | waxing_gibbous_moon_3d.png | |
| Miscellaneous | droplet_3d.png | |
| Miscellaneous | level_slider_3d.png | |
| Miscellaneous | thermometer_3d.png | |
| Miscellaneous | wind_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 RGB | Color in Hex | |
|---|---|---|
| Primary | rgb(15, 4, 76) | #0F044C |
| Secondary | rgb(20, 30, 97) | #141E61 |
| Accent | rgb(120, 122, 145) | #787A91 |
| Text | rgb(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.
- 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
Current moon phase
Hourly forecast
Seven-day forecast
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):
Enter a location into the builder
Click the JSON button
Look over the JSON output of a sample weather query
Use the documentation to look up any field in the JSON response that you are not certain about
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?
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
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
Values fetched by the widget
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.
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:
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.
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:
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'
')';
}
}
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.
@", 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:
@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:
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);
}
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
_ 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:
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,
}
@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:
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!
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:
try {
final Response response = await http.get('https://my-api');
final CurrentWeather weather = CurrentWeather.fromJson(response.data);
return weather;
} catch (e) {
throw Exception(e);
}
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:
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.
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
The URL
The user's location
The API key and options
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.
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:
# 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:
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:
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:
final String? apiKey = dotenv.env['API_KEY'];
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:
final LocationData location = await getLocation();
final double? lat = location.latitude;
final double? lon = location.longitude;
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.
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.
- The URL does not ask for icon set 2. "If you do not include the
iconSetparameter, the Timeline Weather API usesicons1", whose 9 IDs leave sevenWeatherIconvalues unused; add&iconSet=icons2(Visual Crossing, n.d.-a). - The seven-day forecast is daily data. The documentation lists
days,hoursandcurrentas separateincludesections and does not say whetherinclude=hours,currentstill 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). unitGroupalso acceptsukandbasebesidesusandmetric;usis the default (Visual Crossing, n.d.-b).- As in the error-checking snippets, with Dio the call is
dio.get(...).
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.
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
- What does open-source mean? What are some different open-source licenses?
- What are some factors to consider when selecting a data provider, such as a third-party API?
- Why is it important to keep your code organized? What are some ways you can organize it?
- What is an
enum? - What is a decorator?
- What is code generation?
- What package can be used to generate code?
- What case style does Dart prefer for class names? For variable names?
- How can you keep secrets, such as an API key, safe?
- What are some good resources for finding answers to programming questions?
Key terms
Command reference
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
References
- BPB Publications. (n.d.). Flutter for Jobseekers (companion code repository). Retrieved from GitHub: https://github.com/bpbpublications/Flutter-for-Jobseekers (added, not in the book)
- Dart. (n.d.-a). Metadata. Retrieved from Dart: https://dart.dev/language/metadata (added, not in the book)
- Dart. (n.d.-b). Enums. Retrieved from Dart: https://dart.dev/language/enums (added, not in the book)
- Dart. (n.d.-c). Effective Dart: Style. Retrieved from Dart: https://dart.dev/effective-dart/style (added, not in the book)
- flutter_dotenv. (n.d.). flutter_dotenv. Retrieved from pub.dev: https://pub.dev/packages/flutter_dotenv (added, not in the book)
- location. (n.d.). location. Retrieved from pub.dev: https://pub.dev/packages/location (added, not in the book)
- Rousselet, R. (n.d.). freezed and Migration guide. Retrieved from pub.dev: https://pub.dev/packages/freezed (added, not in the book)
- Tom, W. (2022, August 10). Microsoft open sources its 3D emoji to let creators remix and customize them. Retrieved from The Verge: https://www.theverge.com/2022/8/10/23299527/microsoft-emoji-open-source-creators
- Visual Crossing. (n.d.-a). Defining the icon set in the Weather API. Retrieved from Visual Crossing: https://www.visualcrossing.com/resources/documentation/weather-api/defining-icon-set-in-the-weather-api/ (added, not in the book)
- Visual Crossing. (n.d.-b). Timeline Weather API. Retrieved from Visual Crossing: https://www.visualcrossing.com/resources/documentation/weather-api/timeline-weather-api/ (added, not in the book)
Debugging, Troubleshooting, and Performance Considerations
Logging, breakpoints and exceptions, Flutter DevTools, jank and profile mode, ListView vs Column, and how to keep widget rebuilds cheap.
Finding Flutter Jobs
How the Flutter community and recruiters bring jobs to you, and 16 recruiter answers on skills, resumes, seniority and compensation.