arrow_back

Dart: Using Functions with Lists and Maps

Join Sign in

Dart: Using Functions with Lists and Maps

1 hour 30 minutes 1 Credit

GSP1015

Google Cloud self-paced labs logo

Overview

Dart is a client-optimized language for developing fast apps on any platform. Its goal is to offer the most productive programming language for multi-platform development, paired with a flexible execution runtime platform for app frameworks.

Languages are defined by their technical envelope — the choices made during development that shape the capabilities and strengths of a language. Dart is designed for a technical envelope that is particularly suited to client development, prioritizing both development (sub-second stateful hot reload) and high-quality production experiences across a wide variety of compilation targets (web, mobile, and desktop).

Dart also forms the foundation of Flutter. Dart provides the language and runtimes that power Flutter apps, but Dart also supports many core developer tasks like formatting, analyzing, and testing code.

In this lab, you will learn the basics of Dart in a prepared development environment.

What you'll learn

  • Maps

  • Lists

Prerequisites

Based on the content, it is recommended to have some familiarity with:

  • General programming principles

Setup

Before you click the Start Lab button

Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources will be made available to you.

This hands-on lab lets you do the lab activities yourself in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials that you use to sign in and access Google Cloud for the duration of the lab.

To complete this lab, you need:

  • Access to a standard internet browser (Chrome browser recommended).
Note: Use an Incognito or private browser window to run this lab. This prevents any conflicts between your personal account and the Student account, which may cause extra charges incurred to your personal account.
  • Time to complete the lab---remember, once you start, you cannot pause a lab.
Note: If you already have your own personal Google Cloud account or project, do not use it for this lab to avoid extra charges to your account.

Task 1. Getting started

The lab environment includes an Editor and Browser pre-configured for Dart.

  1. Access these resources using the lab credentials panel.

  2. Copy the IDE link and paste it into a new browser.

Task 2. Flutter repository

In the code editor clone the flutter repository and then access the relevant code sample.

  1. In the editor select Source Control.

The Source Control menu, which includes the Open folder and Clone Repository buttons.

  1. Select Clone Repository.
  2. Enter the following repository:
https://github.com/rosera/flutter_workshop.git
  1. Clone to the default directory.
Note: As the repository is cloned, the editor will raise helpful notifications. These are not required for this lab. Alternatively you may use the editor available at dart.dev.

With the Repository now cloned onto your environment. The Flutter Workshop repository is now available. For this lab use the dart folder to complete the exercises.

  1. Select the dart folder.

A solution folder containing working examples is also available in the same repository.

Solution Directory Contents
dart/lab07/solutions Maps
dart/lab08/solutions Lists
Note: Please refer to the correct directory if you need assistance with a solution.

Task 3. Introduction to Dart

Watch the Introduction to Dart video to get an overview of what Dart is and why it is important.

In addition the following guidelines on Effective Dart will be useful.

  • Style Guide – This defines the rules for laying out and organizing code, or at least the parts that dart format doesn’t handle for you. The style guide also specifies how identifiers are formatted: camelCase, using_underscores, etc.

  • Documentation Guide – This tells you everything you need to know about what goes inside comments. Both doc comments and regular, run-of-the-mill code comments.

  • Usage Guide – This teaches you how to make the best use of language features to implement behavior. If it’s in a statement or expression, it’s covered here.

  • Design Guide – This is the softest guide, but the one with the widest scope. It covers what we’ve learned about designing consistent, usable APIs for libraries. If it’s in a type signature or declaration, this goes over it.

Task 4. Getting started with maps

In general, a map is an object that associates keys and values. Both keys and values can be any type of object. Each key occurs only once, but you can use the same value multiple times. Dart support for maps is provided by map literals and the Map type.

Maps, and their keys and values, can be iterated. The order of iteration is defined by the individual type of map. Examples:

  • The plain HashMap is unordered (no order is guaranteed),
  • the LinkedHashMap iterates in key insertion order,
  • and a sorted map like SplayTreeMap iterates the keys in sorted order.

In this section learn how to use Maps in Dart.

Hello maps

Create an application based on the following code.

  1. Create new file hello-maps.dart.
  2. Add the following code:
void main() { Map starWars = { "title": "Star Wars", "year": 1977 }; print (starWars); print (starWars['title']); print (starWars['year']); }
  1. Save the code.
Note: Once the code is saved, a Run|Debug menu option will appear.
  1. Select the Run option to execute the code.

  2. In the debug console the program output will be displayed:

{title: Star Wars, year: 1977} Star Wars 1977

Find a key in a map

Create an application based on the following code.

  1. Create new file key-maps.dart.
  2. Add the following code:
void main() { Map starWars = {"title": "Star Wars", "year": 1977}; Map theEmpireStrikesBack = {"title": "The Empire Strikes Back", "year": 1980}; Map listFilms = {"first": starWars, "second": theEmpireStrikesBack}; if (listFilms['first']==null) { print ('Key does not exist'); } else { print ('Key exists!'); } }
  1. Save the code.
Note: Once the code is saved, a Run|Debug menu option will appear.
  1. Select the Run option to execute the code.

  2. In the debug console the program output will be displayed:

Key exists!

Find a value in a map

Create an application based on the following code.

  1. Create new file value-maps.dart.
  2. Add the following code:
void main() { Map starWars = {"title": "Star Wars", "year": 1977}; Map theEmpireStrikesBack = {"title": "The Empire Strikes Back", "year": 1980}; Map listFilms = {"first": starWars, "second": theEmpireStrikesBack}; Map firstFilm = listFilms['first']; String title = firstFilm['title']; int year = firstFilm['year']; print (title); print (year); }
  1. Save the code.
Note: Once the code is saved, a Run|Debug menu option will appear.
  1. Select the Run option to execute the code.

  2. In the debug console the program output will be displayed:

Star Wars 1977

Adding content to a map

Create an application based on the following code.

  1. Create new file adding-maps.dart.
  2. Add the following code:
void main() { Map starWars = {"title": "Star Wars", "year": 1977}; Map theEmpireStrikesBack = {"title": "The Empire Strikes Back", "year": 1980}; Map listFilms = {"first": starWars, "second": theEmpireStrikesBack}; print(listFilms); print(listFilms['first']); print(listFilms['first']['title']); print(listFilms['first']['year']); print(listFilms['second']); print(listFilms['second']['title']); print(listFilms['second']['year']); }
  1. Save the code.
Note: Once the code is saved, a Run|Debug menu option will appear.
  1. Select the Run option to execute the code.

  2. In the debug console the program output will be displayed:

{first: {title: Star Wars, year: 1977}, second: {title: The Empire Strikes Back, year: 1980}} {title: Star Wars, year: 1977} Star Wars 1977 {title: The Empire Strikes Back, year: 1980} The Empire Strikes Back 1980

Task 5. Working with lists

Perhaps the most common collection in nearly every programming language is the array, or ordered group of objects. In Dart, arrays are List objects, so most people just call them lists.

  • Subclasses of this class implement different kinds of lists. The most common kinds of lists are:

  • Fixed-length list. An error occurs when attempting to use operations that can change the length of the list.

  • Growable list. Full implementation of the API defined in this class. In this section learn how to Lists in Dart.

Hello Lists

Create an application based on the following code.

  1. Create new file hello-lists.dart.
  2. Add the following code:
void main() { List listMonths = ['January', 'February', 'March']; listMonths.forEach(print); }
  1. Save the code.
Note: Once the code is saved, a Run|Debug menu option will appear.
  1. Select the Run option to execute the code.

  2. In the debug console the program output will be displayed:

    January February March

Dereference list items

Create an application based on the following code.

  1. Create new file variable-lists.dart.
  2. Add the following code:
void main() { List listMonths = ['January', 'February', 'March']; String month = listMonths[0]; print(month); }
  1. Save the code.
Note: Once the code is saved, a Run|Debug menu option will appear.
  1. Select the Run option to execute the code.

  2. In the debug console the program output will be displayed:

    January

Adding list items

Create an application based on the following code.

  1. Create new file adding-lists.dart.
  2. Add the following code:
void main() { List listMonths = ['January', 'February', 'March']; listMonths.add('April'); listMonths.forEach(print); }
  1. Save the code.
Note: Once the code is saved, a Run|Debug menu option will appear.
  1. Select the Run option to execute the code.
  2. In the debug console the program output will be displayed:
January February March April

Data types and list items

Create an application based on the following code.

  1. Create new file adding-list.dart.
  2. Add the following code:
void main() { Map<String, dynamic> filmStarWars = {"title": "Star Wars", "year": 1977}; Map<String, dynamic> filmEmpire = {"title": "The Empire Strikes Back", "year": 1980}; Map<String, dynamic> filmJedi = {"title": "The Return of the Jedi", "year": 1983}; List listFilms = [filmStarWars, filmEmpire, filmJedi]; Map<String, dynamic> first = listFilms[0]; print(first); print(first['title']); }
  1. Save the code.
Note: Once the code is saved, a Run|Debug menu option will appear.
  1. Select the Run option to execute the code.
  2. In the debug console the program output will be displayed:
{title: Star Wars, year: 1977} Star Wars

Task 6. Pop quiz

Test your understanding of Maps and Lists by completing the short quiz on the topics covered in this lab.

Congratulations!

You have successfully completed the lab and demonstrated your knowledge of Dart. Over the course of this lab, you have been introduced to the following Dart fundamentals:

  • Maps

  • Lists

Next steps / Learn more

  • Flutter Introduction
  • Flutter Intermediate

Manual last updated September 21, 2022

Lab last tested February 8, 2022

Copyright 2022 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.