arrow_back

Dart: Introducing Class Abstraction

Join Sign in

Dart: Introducing Class Abstraction

1 hour 30 minutes 1 Credit

GSP1016

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

  • Classes

Prerequisites

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

  • General programming principles

Setup and requirements

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.

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 1. 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.
  1. With the Repository now cloned onto your environment select the Open Folder option.

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/lab05/solutions Classes
Note: Please refer to the correct directory if you need assistance with a solution.

Task 2. 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 3. Getting started with classes

Dart is an object-oriented language with classes and mixin-based inheritance. Every object is an instance of a class, and all classes except Null descend from Object. Mixin-based inheritance means that although every class (except for the top class, Object?) has exactly one superclass, a class body can be reused in multiple class hierarchies. Extension methods are a way to add functionality to a class without changing the class or creating a subclass.

In this section learn how to use Classes in Dart.

Hello class

Create an application based on the following code.

  1. Create new file hello-class1.dart.
  2. Add the following code:
class FlutterDev { FlutterDev(String name) { print('I am $name a Flutter Developer'); } } void main() { FlutterDev('Jamie'); }
  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.

In the debug console the program output will be displayed:

I am Jamie a Flutter Developer

Using a class constructor

Create an application based on the following code.

  1. Create new file constructor-class.dart.
  2. Add the following code:
const numDays = 7; class DaysLeftInWeek { int currentDay = DateTime.now().weekday.toInt(); int howManyDaysLeft(){ return numDays - currentDay; } } void main() { var currentDay = DaysLeftInWeek(); print ('Today is day ${currentDay.currentDay}'); print ('We have ${currentDay.howManyDaysLeft()} day(s) left in the week'); }
  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.

In the debug console the program output will be displayed:

Today is day 1 We have 6 day(s) left in the week Note: The above code output will differ based on the day of the week it is ran.

Extending a class constructor

Create an application based on the following code.

  1. Create new file extend-class.dart.
  2. Add the following code:
class Media { String title = ""; String type = ""; Media(){ type = "Class"; } void setMediaTitle(String mediaTitle){ title = mediaTitle; } String getMediaTitle(){ return title; } String getMediaType(){ return type; } } class Book extends Media { String author = ""; String isbn = ""; Book(){ type = "Subclass"; } void setBookTitle(String bookTitle){ title = bookTitle; } void setBookAuthor(String bookAuthor){ author = bookAuthor; } void setBookISBN(String bookISBN){ isbn = bookISBN; } String getBookTitle(){ return title; } String getBookAuthor(){ return author; } String getBookISBN(){ return isbn; } } void main() { var myMedia = Media(); myMedia.setMediaTitle('Tron'); print ('Title: ${myMedia.getMediaTitle()}'); print ('Type: ${myMedia.getMediaType()}'); var myBook = Book(); myBook.setBookTitle("Jungle Book"); myBook.setBookAuthor("R Kipling"); print ('Title: ${myBook.getMediaTitle()}'); print ('Author: ${myBook.getBookAuthor()}'); print ('Type: ${myBook.getMediaType()}'); }
  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.

In the debug console the program output will be displayed:

Title: Tron Type: Class Title: Jungle Book Author: R Kipling Type: Subclass

Extending a class with Mixins

Create an application based on the following code.

  1. Create new file mixins-class.dart.

  2. Add the following code:

abstract class SnickersOriginal { bool hasHazelnut = true; bool hasRice = false; bool hasAlmond = false; } abstract class SnickersCrisp { bool hasHazelnut = true; bool hasRice = true; bool hasAlmond = false; } class ChocolateBar { bool hasChocolate = true; } class CandyBar extends ChocolateBar with SnickersOriginal { List<String> ingredients = []; CandyBar(){ if (hasChocolate){ ingredients.add('Chocolate'); } if (hasHazelnut){ ingredients.add('Hazelnut'); } if (hasRice){ ingredients.add('Hazelnut'); } if (hasAlmond){ ingredients.add('Almonds'); } } List<String> getIngredients(){ return ingredients; } } void main() { var snickersOriginal = CandyBar(); print ('Snicker Original Ingredients:'); snickersOriginal.getIngredients().forEach((ingredient) => print(ingredient)); }
  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.

In the debug console the program output will be displayed:

Snickers Original Ingredients: Chocolate Hazelnut

Task 4. Pop quiz

Test your understanding of Dart Clases 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 been introduced to the following Dart fundamentals:

  • Classes

  • Methods

  • Constructors

  • Mixins

Next steps / Learn mre

  • Flutter Introduction
  • Flutter Intermediate

Manual Last Updated October 3, 2022

Lab Last Tested February 8th, 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.