0% found this document useful (0 votes)
11 views

Bim30603chapter3 Mobileapplicationprogramming Part2 Dart

Uploaded by

Solehudin Yusuf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Bim30603chapter3 Mobileapplicationprogramming Part2 Dart

Uploaded by

Solehudin Yusuf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 294

Chapter 3

Mobile Application
Programming: Part 2
BIM30603 Mobile Application Development

Department of Multimedia
Faculty of Computer Science and Information Technology
TABLE OF
CONTENTS
01 Dart: First Step to Flutter
02 Your First Dart Application
03 Data Types & Variables
04 Operators
TABLE OF
CONTENTS
05 Collection
06 Control Flow
07 Exploring Function
08 Classes
Learning Outcome
At the end of this chapter, students will be able to:
● Discuss the basics and concepts of Dart language in Flutter.
● Explain the fundamental of Dart language
● Write program code using Dart.
Dart: First Step to Flutter
Dart: A History
● Dart 1.0 was released on November 14th, 2013 by
Google and was founded by Lars Bak and Kasper Lund.

● It aims to help developers build modern web and


mobile applications.

● It covers client, server, and now mobile with Flutter.


● Coming with a range of tools including a virtual
machine, core libraries and package management
repository, it lends enough ammunition for you to get
started on your next project.
What’s up with “Dart”!
● Dart is Object-Oriented
● Smalltalk was released in the 1970s and was one of the first pure object-
oriented programming languages.
○ You can now find object-oriented programming everywhere.

○ It has dominated the world of programming languages.


What’s up with “Dart”!
● The concept behind object-oriented programming is quite simple: all but the
most trivial programs require a particular form of structure.

● The most clear-cut way of achieving this particular structure is by using the
concept of storage containers.
○ A programming language can be divided into data and operations to be performed on data.

○ We can store specific data and operations in some type of container.

○ Furthermore, these containers are made to be general.

○ Hence, they not only store data and operations but they are themselves values that can be
stored in other containers and passed as parameters to other operations.

○ In object-oriented programming, these containers are known as objects.


What’s up with “Dart”!
● Alan Kay, the inventor of Smalltalk, remarked that in this way the simplest
object has the same construction principle as a full computer: it combines
data with operations under a formalized interface.

● And now, even though object-oriented programming can be found in a


multitude of languages, very few actually follow the principles set by
Smalltalk.
○ Dart, on the other hand, is a pure object-oriented programming language with every value being
an object.
Dart: Through the Eyes of JavaScript
● Dart is a clean, simple, class-based object-oriented language that has more
structure than JavaScript, the programming language it is heavily based on.
○ It’s great for developers that are interested in having a structure in their programming
language so that they can easily do refactoring and build large web applications.

● According to the founders, one of the things they focused on while creating
the language is that it be compatible with the web.
○ Hence, one of the most important components is the Dart to JavaScript compiler.

○ It translates the Dart source code to JavaScript and ensures that you get the same semantics as if
you run it on top of the JavaScript virtual machine.
Dart Basics
● Flutter uses Dart language to build Apps.
● Flutter and Chrome use the same rendering engine — SKIA.
○ https://skia.org/

● Instead of interacting with native APIs, it controls every pixel on the screen,
○ which gives it the much necessary freedom from the legacy baggage as well as the performance
it has
Why Flutter Uses Dart
● https://flutter.dev/docs/resources/faq#why-did-flutter-choose-to-use-dart
● https://hackernoon.com/why-flutter-uses-dart-dd635a054ebf
● You can follow up with Dart updates on their medium account
(https://medium.com/dartlang)
Using Dart in Flutter
● Flutter has more app-specific libraries, more often on user interface
elements like:
○ Widget: common app elements, like the Text or ListView.

○ Material: containing elements following Material design, like


FloatingActionButton.

○ Cupertino: containing elements following current iOS designs, like


CupertinoButton.
DartPad
● Edit your code on DartPad (https://dartpad.dartlang.org/ or
https://dartpad.dev) for starters and get a better grip.

● I’m sure you’ll be up and running in no time!


Running Dart Console Application in VS Code
1. Open VSCode
2. Press ctrl + shift + p on windows or cmd + shift + p on Mac
3. Choose Dart: New project

1. Then you should select Console Application

1. After locating console application everything is ready for you


Running Dart Console Application in VS Code
Well, how to run it? So easy!!!

1. Just go to terminal > go to file


folder (“cd bin”) and type: "dart
main.dart"

2. or copy the main.dart path then


type: "dart (paste main file path)"

3. or Main Menu > Run > Run


Without Debugging

4. or press ctrl + F5
Setting up Flutter
● Flutter is relatively straightforward to set up and depending on what OS
you’re using; you can check out the steps in this official Flutter tutorial:

○ https://flutter.dev/docs/get-started/install

● But in case, you do run into something, check out here:


○ https://github.com/flutter/flutter/wiki/Workarounds-for-
common-issues#flutter-installation
Setting up Flutter
● The reason we ask that you setup Flutter before Dart is because when you
install Flutter, you install Dart too,
○ and while you can separately install Dart, it would be an unnecessary step.

● Flutter will decide which Dart version will be used, so installing different
Dart version will be ambiguous as well.
Your First Dart Application
The Main Entry Point
● Every application has some point in its program that serves as the entry
point to the application.
○ When an application runs, it starts from that specified entry point.

● In Dart, the entry point is the main() function.


● When you run a Dart program, the compiler looks for the main() function
and executes the code written in that function.
○ If main() is not found, you will get an error and your application won’t run.
The Main Entry Point
● The code you write in main() is encapsulated in curly brackets ({}).

● The keyword main is followed by a set of parentheses (()) which is followed


by an opening curly bracket ({).
○ Start writing your code from the next line and when you’re done, insert a closing
curly bracket (}) in the line after the last line of your code.

○ Insert Code Here is where you write the code for the functionality you want
your application to perform.
Hello World

● Let’s look at the famous “Hello World” program which is usually the first
application you learn to code when learning a new programming language.

● The purpose of the application is to simply print “Hello World”.


The Print Statement
● On line 3 of the program, we are using a
print statement which prints the text
Hello World.

● print() is used to display the output of the code on the console.

○ It follows this syntax:

● Since Hello World is text, to be able to print it, we need to enclose it in


quotation marks.
○ The syntax for displaying text is as follows:
Nothing Without a Semicolon
● You might have noticed that the print statement on line 3 ends with a
semicolon.

● In Dart, just as most programming languages, each statement needs to end


with a semi-colon for the program to execute successfully.

● Try removing the semi-colon in the code snippet above and see what
happens.
Comments
● Line 2 of the program is a comment.
● Comments come in handy for developers that want to read or study code
someone else has written.
○ They enable you to write descriptions about the code without it affecting the
program in any way.

● Our comment is letting the reader know that the program is printing the text
Hello World.

● The general syntax is as follows:


Imperative Programming
● The code that appears inside of the main() function gets executed in order of
appearance.
○ Let’s modify the code in the snippet above and try printing From Dart along with
Hello World.

○ When you run the code above, the print statement on line 2 will execute first and
then the second print statement on line 3 will execute.

● This style of programming is called imperative programming.


Imperative Programming
● It is essentially a programming paradigm wherein you write a set of
instructions that execute in sequential order.

● Imperative programming doesn’t necessarily describe what the program


should accomplish, rather it shows how the program should accomplish it.

● So, in this case, we have created a program that goes first and prints out the
text Hello World and then moves on to the next line and prints the text From
Dart.
A Simple Interactive Program
● The Hello World program we wrote in a previous lesson was simply
displaying some output.
○ But in many cases, we come upon scenarios where we need to take input from the
user and print that input onto the console.

● Let’s write a program for a personalized greeting application.


○ The program will ask the user for their name and then display a personalized
greeting for that user.
A Simple Interactive Program
● The coding program in this lesson
requires input from the user in order
for it to execute successfully.

● On line 1 of the code above, we are importing the dart:io library.


● In computer programming, a library is a collection of similar code that you
can reference in your own code.
○ When you import a library, you can access all the code in that library.

● Every library has a particular purpose.


○ The dart:io library provides I/O (Input/Output) support for non-web applications.
○ We imported dart:io because the program we wrote requires input from the user.
A Simple Interactive Program
● Dart provides multiple methods that can be used to take external input from
a user depending on the type of input required by the program.
○ For this course, we will be using the readLineSync() method (function) which
reads a line from the input.

● The complete expression we will use is stdin.readLineSync()


○ stdin stands for standard input, letting the compiler know that the program
specifically requires some sort of input from the user.
○ readLineSync() is a built-in method which we have already discussed above.

● Line 4 is displaying Hello and then joining it with the input provided by the
user using the string interpolation ( ${expression} )
Challenge: Displaying Output
● In this challenge, your task is to display some text.
● The text you have to display is a famous movie quote.

● If your code doesn’t match the quote exactly, it won’t pass the test case, so be
careful.
Data Types and Variables
A Brief Introduction to Objects: Objects in Reality
● Objects are all around us.
○ From the food we eat to the pets we own,
everything is an object.

● Every object has characteristics and


behaviors.
○ For instance, a person has characteristics
such as their name, age, and height.

○ A person can also perform behaviors such


as walking, eating, and sleeping.

○ These characteristics and behaviors


combined define who the person is.
A Brief Introduction to Objects: Objects in Dart
● In the same way, everything in Dart is an object.
● Objects in a programming language also have characteristics known as
properties and they can also perform behaviors known as methods.
○ Properties represent what the object knows.

○ Methods represent what the object can do.


What Are Variables?
● Variables are used for storing information which can then be used by the
computer program.

● Imagine you’re building a wooden bookshelf and need planks of wood, nails,
and different tools to finish your project.

● To better organize the material, you decide to group similar items together
and store them in boxes.

● This would allow you better access to each item depending on which item
you need and when you need it.
What Are Variables?
● You have one box with planks, another with nails, and another with tools.
● However, there’s a problem; you have multiple types of planks, nails, and
tools.

● You have to sort through the right type of box to get the required item.
● You decide to further divide each box.
● Multiple boxes can store the same type of item, such as wooden planks, but
each box is still unique.
What Are Variables?
● There are now two boxes for wooden planks; one with wide planks and
another with narrow planks.

● When you’re done dividing all the material into separate boxes, you end up
with an abundance of boxes and can’t seem to find what you’re looking for.

● Finally, you label each box with a unique name to make each one easier to
identify.

● You now have an organized way to store your material and access it
whenever you want.
What Are Variables?
● In the same way, a variable
is a small box used to store
data.

● When we assign a value to a


variable, we are basically
putting something in a box.

● When you declare a


variable, you give it a unique
name or identifier, define
the type of data it can store,
and set its initial value.
Declaring a Variable in Dart
● We start off by mentioning the type of data our variable will hold, such as an
integer.

● Then comes the variable’s unique name, followed by an equal sign ( =), and
the initial value.

● Don’t forget the semicolon at the very end.


Declaring a Variable in Dart
● Now, let’s map the syntax to the actual code in Dart:

● In the code above, we are declaring a variable with the name


myFirstDartVariable.

● myFirstDartVariable can store data of type int (integer) and is assigned an


initial value of 5.
Printing Variables
● The basic syntax for using the print statement is as follows:

● Now that we have learned how to declare a variable myFirstDartVariable;


let’s learn how to print it.

● In the code snippet above, we simply passed the name of our variable to the
print statement and in return, the value assigned to the variable, i.e. 5, was
displayed.
Data Types
● The data type of an item or variable is an attribute that tells us what kind of
data that variable can have.
○ This is similar to when we specified which types of items can be stored in our
boxes in the previous lesson.

● Data types can be found all around us; numbers, alphabets, or characters
which are classified based on the similar properties they share.
Dart’s Built-In Data Types
● The Dart language has special support for the following types:
○ Numbers

○ Strings
○ Booleans

○ Lists

○ Sets

○ Maps

○ Runes
○ Symbols
Values and References
● Data types can be broadly divided into two categories:
1. Reference type

2. Value type

● The information provided by a value type is the value itself.


● For a reference type, the information it provides is a reference to some
object, i.e., the memory address of where an object is stored.
Values and References
● To make this clearer, let’s look at this using physical objects.
○ Imagine you have a piece of paper.

○ You want the paper to hold some information, such as your name.
○ You can write your name on the piece of paper; therefore, the value of the paper is
the same as the information it provides.

○ This is an example of value type.


○ If someone wants to know your name, all they have to do is read the paper.
Values and References
● Now imagine, you want the paper to hold your house.
○ That’s not physically possible, so you write the address to your house, hence the
value of the paper is a reference to the required information.

○ This is an example of reference type.


○ If someone wants to go to your house, they will first have to read the address on
the paper and then get directions to your house.

○ In the same way, a reference type holds the memory address location of the value,
while value types hold the value themselves.
Data Types Are Objects
● In most languages, primitive data types are value types,
○ but in Dart, all data types are objects.

● This means that even primitive data types are reference types.
● Therefore, we can say that in Dart, variables specifically store references
and are referring to objects.
Literals
● We will be using the word literal throughout the course, so let’s take a
closer look at what a literal actually is.

● A literal is defined as taking anything in its most usual and basic sense.
● Mapping this onto computer programming, literals are fixed values
appearing directly as they do in the source code.

● For example, Hello World, 5, and A are all literals.


The num Type
● If we want a variable that has a number value, we will declare it using the num
data type.

● The basic syntax is as follows:

● Let’s look at an example.


The num Type
● Dart numbers are further divided into two subtypes:
1. integers (int)

2. doubles (double)

● Both int and double are subtypes of num.


Integers
● Integers are whole numbers without a decimal point.

● In the code snippet below, we are declaring two variables of type int.
○ The first variable is a simple integer while the second variable is a hex number.

● The basic syntax is as follows:


● Let’s look at an example.
Doubles
● Doubles are numbers that include a decimal point.

● In the code snippet below, we are declaring two variables of type double.
○ The first variable is a simple double while the second variable is an exponent.

● The basic syntax is as follows:


● Let’s look at an example.
Doubles
● As of Dart 2.1, integer literals are automatically converted to doubles when
necessary.

● When you run the code snippet below, the output displayed will be 1.0
rather than 1.
Strings
● A Dart string is a sequence of UTF-16 code units.
● UTF stands for Unicode Transformation Format.
● Unicode is a set of characters in which each character is a unique code unit.
String Literals
● At face-value, string literals are simply text encapsulated in quotation
marks.
String Literals
● All we are doing in the code snippet
above is printing strings using multiple
techniques.
● They all are pretty straight forward
except for maybe line 9.

● On line 9 we are using single quotes to create a string, however, the


string itself has a single quote in the word It’s.
○ If we print the string as-is, 'It's possible with an escape character',
we will get an error because the compiler will see the single quotation in the
word It's as the closing quotation of the string.
○ To solve this problem, we can use an escape character (\) which tells the
compiler to escape the built-in functionality of the single quotation and
evaluate it as a string.
Defining a String Variable
● If we want to define a variable that stores values of type String, we would use
the following syntax:

● Let’s map the syntax onto some actual Dart code.


String Concatenation
● To concatenate two strings means to join them together.
● Concatenation of two or more strings is done using the + operator.

● The code above is pretty simple.


○ On line 4 we are concatenating the first string, s1, and the second string, s2, and
then printing the concatenated string.
String Interpolation
● String interpolation is the ability to create new strings or modify existing
ones by embedding them with expressions.

● Expressions are evaluated, and the resulting values are converted into
strings and concatenated with the enclosing string.

● Interpolation is Dart’s more concise and efficient alternative to string


concatenation.

● However, string interpolation is a lot more complex than simple


concatenation which allows a lot more flexibility.
String Interpolation: Syntax
● An un-escaped $ character in a string signifies the beginning of an
interpolated expression.

● The $ sign can be followed by a single identifier id that does not contain the
$ character.

● The $ sign can also be followed by an expression delimited by curly brackets.


String Interpolation: Learning by Example
● Let’s look at some different coding examples to get a better idea of how
string interpolation works.

● In the above code, assign a value to the country variable based on the
country you want to visit.

● Instead of changing the print statement each time, all we have to do is


change the value of the variable being interpolated.
String Interpolation: Learning by Example
● Let’s now try to embed a mathematical expression in a string using the curly
brackets ({}).

● In the code above, 5+3 is our expression which the compiler processes and
interprets to 8, as can be seen in the output when you RUN.
Multiple Lines
● You can concatenate strings using adjacent string literals as well.

● Notice how we have used both double (") and single (') quotation marks.
● When we run the code snippet above, we get one complete string on a single
line.

● But what if we actually wanted to have a string on multiple lines?


Multiple Lines
● You can create multiline strings in Dart.
● To do so, you simply write your string as you want
to print it and surround it with three double
quotation marks or three single quotation marks.

● Let’s look at an example below.


Challenge: Embed a Variable in a String
● You are given two variables, name and age, which store a person’s name and
age respectively.
○ You have to embed name and age in a larger string and print the final string.

● Input
○ The input is the variables name and age .

● Output
○ The output will be the final in which you will embed name and age .

● Sample Input:
● Sample Output:
True & False
● Dart’s bool type represents boolean values.
○ Only two objects have type bool, the boolean literals true and false.

● In the code snippet below, we are declaring a variable b1 of type bool and
assigning it an initial value of true.

● The basic syntax for declaring a variable of type bool is as follows.


Type Inference
● Dart is strongly typed.
● Strongly typed languages take extra precautions and have rules and
restrictions to ensure that a variable’s value always matches the variable’s
static type.

● Although types are mandatory in Dart, type annotations are optional


because of type inference.
What is Type Inference?
● As the name implies, type inference is a programming language’s ability to
infer types when not specified by the user.

● Until now, we have been declaring a variable using the following syntax:

● Type inference allows us to declare a variable without explicitly mentioning


the data type.

● In Dart, we insert the var keyword in place of the data type.

● Variable types are inferred from their initial value if any.


What is Type Inference?
● Let’s look at an example:

● When you press RUN the program should successfully execute.


● But how do we know if bookTitle is even being declared as a String?
Checking the Type
● Remember when we said objects have properties which represent the
information the object knows?
○ Well, runtimeType is one such property that holds information about the data
type of the variable.

● In the code snippet below, we are printing the data type of the variable
bookTitle by calling its property runtimeType.

● When you press RUN, the output should display String.


○ This confirms that bookTitle has been inferred as a String and we cannot
assign it a value of any type other than String.
Using Type Annotations
● Remember when we said that variable types are inferred from their initial
value?
○ It’s also important to mention that subsequent assignments are not considered.
○ This means that too precise a type may be inferred. If that is not desired, you can
add type annotation.
● In the example below, we are declaring a variable, number, using the var
keyword.
○ We want the variable to hold any type of number, i.e.,
int and double.
○ When you run the code snippet, you will get an error.
○ When we initialized number with an integer, the
compiler inferred that number is of type int.
○ Hence, when we reassigned it a value of type double,
the compiler displays an error.
Using Type Annotations
● Here, we can use type annotation and declare the number variable using the
num data type.

● Remember that type num is generic enough to hold both int and double.
Dynamic Types
● If you want a variable to hold objects of many types, you can declare a
variable using the dynamic keyword.

● In the code snippet above, we are declaring a variable dynamicVariable and


initially assigning it a value of type String.

● We then go on to reassign it a variable of type int and then finally a value of


type bool. The code runs smoothly without any errors.
Defining Constants
● Sometimes we create a variable and assign it a very specific value with the
intention of never changing the value.

● For the program to run successfully, it is of the utmost importance that the
value of the variable remains the same throughout its lifetime.

● To create such a variable, the keywords final and const should be used.
● Before we get into what final and const actually do, we need to learn the
difference between compile-time and runtime.
○ Compile-time and runtime are programming terms that refer to different stages
in a program’s lifetime.
○ In order to create a program, you first write some source code.
○ The source code defines how the program will function.
Compilation and Compile-Time
● Computers don’t understand the code we write in different programming
languages.
○ They only know one language: machine language, 1’s and 0’s.

○ The source code must be compiled into machine code in order for it to be
executable.

○ This process is referred to as compilation.

● Now that we know what compilation is, let’s take that as our base and learn
about compile-time through an example.
Compilation and Compile-Time
● We have been defining some int and double variables in our programs with
initial values.

● These variables will always have the same initial value whenever we run the
program.

● These values are fixed at the time of compilation.


● Such things are said to be fixed at compile-time.
Run and Run-Time
● After a program is compiled, we can run it.
● When we took user input from the user, we could point out that the value
displayed by the print statement could change every time we run the
program, depending on what the user types.

● Things that can’t be determined until the program is actually run are said to
be fixed at run-time.
Never Changing Variables
● To create variables whose values cannot be changed, Dart provides the
keywords final and const.

● Instead of declaring a variable using var or a data type, we use final and
const.
Using final
● A final variable (a variable created using the final keyword) is initialized the
first time it is used and can only be set once.

● In other words, the final value will be known at runtime.

● If we try to reassign a value to the name variable, we will get an error.


Using const
● A constant variable (a variable created using the const keyword) should be
created when you know the value at compile-time.

● Like a final variable, a constant variable can also only be set once

● Again, if we try to reassign a value to the name variable, we will get an error.
final vs const

● The difference between the two might not be apparent here as the use of
const and final usually comes in more complex programs.

● All you need to know is that while both final and const variables can only
be set once,
○ final variables may be set at either run time or compile time,

○ const variables can only be set at compile time.


Operators
Types of Operators
● Operators are symbols that perform operations used for modifying or
manipulating data.

● Manipulating data is an essential part of any programming language, and


Dart is no different, providing a rich set of operators for its basic types.

● The following are built-in operators in Dart:


○ Arithmetic Operators
○ Equality and Relational Operators
○ Type Test Operators
○ Assignment Operators
○ Logical Operators
○ Bitwise and Shift Operators
Operators and Expressions
● An Expression is a special type of statement that evaluates to some value.
○ For instance, in mathematics, 1 + 1 is an expression because it evaluates to 2.

● Expressions are composed of two things; operands and operators.

● Operators usually follow an infix notation.


○ The infix notation is where the operator is situated between two operands.

● Operands are the data objects that the operator is performing an operation
on.
○ In other words, operators define how the operands are to be processed to
produce a value.
Arithmetic Operators
Arithmetic Operators
● Taking the first operand to be 10 and the
second operand to be 7, let’s look at an example
for each operator.
● Most of the operators are ones we see regularly
in mathematics.
○ The only one that might be new is ~/.
● All ~/ does is divide both operands, remove
the fractional part from the decimal value, and
keeps the whole number.
● The difference is clear on line 9 and line 10 of
the code above.
Prefix and Postfix Operators
● Below is a list of the arithmetic prefix and postfix increment and decrement
operators supported by Dart.
The ++var expression
● The expression value of ++var is var+1.
● When we insert the expression in a print statement, the compiler first
increments the variable by 1 and then prints the value of the variable.

● Since the value displayed is after the increment, 6, i.e., 5+1, is displayed as
the output.
The var++
● The expression value of var++ is var.
● When we insert the expression in a print statement, the compiler first prints
the value of the variable and then increments it by 1.

● Since, in this case, the print statement will display the variable value first
and then increment it, 5 is displayed on line 4, whereas when the print
statement is called again the value has already been incremented hence,
line 5 displays 6.
The --var expression
● The expression value of --var is var-1.
● When we insert the expression in a print statement, the compiler first
decrements the variable by 1 and then prints the value of the variable.

● Since the value displayed is after the decrement, 4, i.e., 5-1, is displayed as
the output.
The var-- expression
● The expression value of var-- is var.
● When we insert the expression in a print statement, the compiler first prints
the value of the variable and then decrements it by 1.

● Since, in this case, the print statement will display the variable value first
and then decrement it, 5 is displayed on line 4, whereas when the print
statement is called again the value has already been decremented hence,
line 5 displays 4.
Equality and Relational Operators
● Relational operators are operators that perform operations that compare
operands of numeric types, for example, less than and greater than.

● Equality operators can compare operands of any type and are two in number
(== and !=).
Equality and Relational Operators
Relational Operators
Equality Operators
Equality Operators
● We can also use equality operators on non-integer literals such as string
literals.

● Let’s look at an example where the first operand is a and the second operand
is b.
Type Test Operators
● Type test operators are operators that can be used to check the type of an
object at runtime.

● Below is a list of the type test operators supported by Dart.


Type Test Operators
● While type test operators do have two operands, the order of the operands is
important.

● The value whose type needs to be checked should be on the left of the
operator and the type itself should be on the right of the operator.

● The basic syntax is as follows:


Type Test Operators
● Let’s look at some examples of how we can use type test operators in Dart.
● Line 7 displays false because type1 is of type double and
we are asking the compiler if it is of type int.

● Line 8 displays true because type2 is of type int and we


are also asking the compiler if it is of type int.

● Line 9 displays true because type3 is of type String and


we are also asking the compiler if it is of type String.

● Line 10 displays false because type4 is of type bool and


we are asking the compiler if it is of type double.

● Line 11 displays true because type4 is not of type double


and we are also asking the compiler if it is not of
type double.
Assignment Operators
● Assignment operators are used for performing operations that assign a
value to an operand.

● They are modified versions of all the operators we have discussed so far and
the operators we have yet to discuss.

● We have already seen how the = operator can be used to assign values; we’ve
been using it since the start of this course.
Compound Assignment Operators
● Compound assignment operators combine other operators with the
assignment operator (=)

● Here is their general syntax:


○ What’s happening is that the operator is performing an operation on operand1
and operand2 and then assigning the resultant value to operand1.

● It’s equivalent to the following:


The += operator

● Before reassigning the variable A, its value was 10.


● After using the compound assignment operator +=, its new value is 17.
● Here, A += B is equivalent to A = A + B.
The &= operator

● Here, A &= B is equivalent to A = A & B.


The ~/= operator

● Here, A ~/= B is equivalent to A = A ~/ B.


Logical Operators
● Logical operators are operators that perform logic operations such as the
Logical AND and Logical OR.
○ They take bool type operands and yield bool type results.
Follow the Rules
● expr is an arbitrary expression that can be
replaced with an operand of type Boolean.

● The operand can be true or false itself or


can be an expression that reduces to true
or false.
Logical Operators: Example
● Let’s now see the above rules in action. For example, our arbitrary
expression expr will be A && B where A is true, and B is false.

● A && B reduces to false as B is false and from our list of rules, we know
that false && expr --> false.
Challenge: Using Multiple Operators
● You are given a variable, check, which stores an integer value. You have to
create a variable compareCheck which checks if the value stored in check is
less than 75 and greater than or equal to 8. The result should be true if it is
between 8 and 75, and false if it isn’t.

● The input is the variable check.


● The output will be the value assigned to compareCheck.
Operator Precedence
● Operator precedence determines the order with which different parts of the
code/expression should be evaluated.

● For instance, 1 + 1 * 5 would give us 6 rather than 10 as * has higher


precedence than +.

● If we wanted 10 we could write the expression as (1 + 1) * 5 as () has higher


precedence than *.
Description Operator

Unary postfix ., ?., ++, --, [``], ()


Precedence Table Unary prefix -, !, ˜
, ++, --, await

Multiplicative *, /, /̃, %

● Operator precedence Additive +, -

being highest at the Shift <<, >>, >>>

top and getting lower Bitwise AND &


as you come down. Bitwise XOR ˆ

Bitwise OR |
● Each operator has a
Relational <, >, <=, >=, as, is, is!
higher precedence
==, !=
than the operators in Equality
&&
the rows that follow Logical AND

it. Logical Or ||

If-null ??

Conditional ?:

Cascade ..

Assignment =, *=, /=, +=, -=, &=, ˆ=, etc.


Challenge: Temperature Conversion
● You are given a variable, fahrenheit, which stores a temperature in degrees
Fahrenheit.

● You have to create a variable, celsius, which converts the temperature


stored in fahrenheit to degrees Celsius.

● To convert temperature from degrees Fahrenheit to degrees Celsius, you


first need to subtract 32 from the temperature, then multiply it by 5,
followed by a division by 9.

● The input is the variable fahrenheit.


● The output will be the value assigned to celsius.
Dart’s Collection
Functions
● In computer programming, a function or a method is a block of code that
performs a specific task.

● The block of code is given a name, much like a variable.


● The function is called using this name whenever that specific task needs to
be performed.

● This removes the need to type the same code over and over again; all you
have to do is call the function’s name.
Functions: How Do They Work?
● Like mathematical functions, programming functions take in an input,
known as an argument, perform some operations on that input, and then
return the resulting output.

● It’s almost like a conveyer belt in a factory with items entering the machine
from one end of the conveyer belt and coming out, completely modified, on
the other end.
○ However, as the machine remains the same throughout its life, it will modify
every item that enters it the same way.
Functions in Dart
● We can divide functions into two broad categories:
○ Built-In Functions

○ User-Defined Functions

● User-defined functions are functions that users create themselves.


● Built-in functions are functions that are predefined by Dart and are part of
their libraries.
○ All we have to do to use them is call their function name.
The print function
● In the code above, print is a method
that performs the specific task print.

● printMe is the argument we pass to the method and “Hello World” is the
resultant output.

● While print is a method, it is a very simple one which only requires passing
it an argument that can be of any type.
○ However, most methods require you to call them on an object.
○ For example, objectName.method(arguments) means that the method is
being called on objectName and arguments are parameters passed to the
method.
○ The method will perform some action on the data stored in objectName.
The indexOf function
● Most methods allow you to only pass an argument of a specific data type.
○ Let’s call one of Dart’s built-in methods, indexOf to get a better idea of how this
works.
● indexOf is called on a string and you pass it one argument of type String.
○ It is used to calculate the starting index of a specified substring within a string.

● In the code above, text is the object we are calling the method indexOf on
and ll is the argument we are passing it.
○ The output is 2 as the starting index of ll is located at the 2nd index in the
string “Hello World”
Collections
● Collections are objects that group other objects together according to a
conceptual schema.
○ For example, a dictionary is a collection of words and a card deck is a collection of
cards.

● Another name for collections is data structures and there is a good reason
for that.
○ Data structures are a means of structuring data.

○ They are used to store, manipulate, and retrieve all types of data.
Dart’s Collection
● Unlike most programming languages, Dart doesn’t have a large collection of
built-in data structures.

● Rather, it has three core built-in collections that can be used to create
collections based on an individual’s needs.
List: The Dart Array
● Arrays are one of the most common and most popular data structures
provided by a programming language.
○ That being said, there are no arrays in Dart.

○ Instead, Dart has lists which provide more or less everything an array provides.

● Lists are an ordered collection of objects.


● This means that every element in a list has a fixed position.
● Use a List when you need to access objects by index.
Creating a List: Using Literals
● The simplest way is using literals along with square brackets ([]).
● The general syntax is as follows:

● We start off with the var keyword followed by a unique identifier


(listName).

● After the equals sign (=), we insert the opening square bracket ([) which is
followed by the elements we want in our list, with each element being
separated by a comma (,).

● After the last element, we insert the closing square bracket (]).
Creating a List: Using Literals
● Let’s look at how this would look in actual code.

● On line 2 of the code snippet above, we are declaring and initializing a list
with three elements.

● When we print the list using the simple print method, the complete list,
including square brackets, is displayed.
Creating a List: Using a Constructor
● You can also declare a list using a List constructor.
● A List constructor creates an object using the List keyword followed by
parenthesis (()).

● The general syntax is as follows:


● When we create a list using the syntax above, we end up with an empty list.
Creating a List: Using a Constructor
● Let’s look at an example below:

● When we print listOfVegetables in the code snippet above, we get an


empty list (square brackets with no elements).
Creating a List: Specifying the Type
● Instead of depending on Dart’s type inference, we can specify the type that a
list should contain.

● Let’s make sure our listOfVegetables can only store strings.

● On line 4 of the code snippet above, we are checking if the type of


listOfVegetables is List<String> using the is operator.

● When you press RUN, true should be displayed as the output.


Working with Lists: Indexing
● Lists use zero-based indexing.
● This means that the first element of a list is located at the 0th index.

● Since each element has its own position, a list can contain duplicates of a
single element because each duplicate is still unique in its position.
○ For instance, we can have a list with five identical elements as shown below.
Working with Lists: Accessing an Element
● To access an element at a particular index we can use square brackets ([]).
● The general syntax is as follows:

● Let’s look at an example below.

● In the code snippet above, we are accessing the second element of the list
listOfVegetables, which is the element at the index 1.
Working with Lists: Finding the Length of a List
● The length of a list is simply the number of elements in that list. To find the
length of a list, we can access the length property.
○ To access any property we use the dot operator (.).

● The basic syntax is as follows:


● Let’s find the length of our listOfVegetables.

● The number 3 should be displayed because listOfVegetables has three


elements.
Working with Lists: Adding a Single Element
● We can add a single element to the end of an existing list using the add
method.
○ The element you add must be of the same type as the elements of the list.

● The add method has a single parameter which is the element you want to add
to a list.
○ The type of the parameter depends on the list you call the method on.

● The general syntax is as follows:


Working with Lists: Adding Multiple Elements
● We can add multiple elements to an already existing list using the addAll
method.
○ Again, the elements you add must be of the same type as the elements of the list.
● The addAll method also has a single parameter which is a list.
○ The list should contain the elements you want to add to an already existing list.
○ The type of the parameter is List<dataType>, where the data type depends on
the list you call the method on.
● In conclusion, addAll basically merges the elements of two lists into one.
● The general syntax is as follows:
Working with Lists: Adding Multiple Elements
● Let’s add some more vegetables to our listOfVegetables.
Working with Lists: Removing a Single Element
● To remove a single element from an already existing list, we can use the
removeAt method which removes the element at the specified index.

● The removeAt method has a single parameter which is the index of the
element you want to remove.
○ The type of the parameter is int.

● The general syntax is as follows:


Working with Lists: Removing a Single Element
● Let’s remove some vegetables from listOfVegetables.
Working with Lists: Removing a Single Element
● If you know which element you want to remove but don’t know its index, you
can use the indexOf method we discussed in a previous lesson to find the
index of an element.

● Let’s find the index of ‘carrot’ and remove it from our listOfVegetables.

● The final listOfVegetables now only contains two elements, namely


‘cucumber’ and ‘zucchini’.
Working with Lists: Removing All Elements
● To remove all the elements from a list, we can simply call the clear method
which takes no parameters.

● Let’s remove all the elements from listOfVegetables.

● When you RUN, an empty list should be displayed.


Working with Lists: The map() Method
● The List type has a method known as map(), not to be confused with the
Map collection.

● map() maps all the items of a list to an expression or statement.


○ For instance, we could have a list of integers and we want to calculate the square
of each integer in the list.
○ map() could be used to solve such a problem.
Working with Lists: The map() Method
● Let’s look at the syntax below.

● Iterator can have any name.


● It is basically a variable that takes the value of each item in the list one by
one.
○ The iterator starts equal to the first item in the list and will then apply that item to
the statement.
○ Then, it will be assigned the second item in the list and apply that item to the
statement.
○ This process will continue until there are no more elements in the list.
Working with Lists: The map() Method
● In the example below, we have our list of vegetables and we want to print “I
love vegetable”, for each of the items.

● The code in Dart is as follows:

○ You might have noticed that the output is not a list, as it does not have square
brackets. To transform the result of map() to a list we can use the toList()
method.

○ When you run the code above, you will see a list as the output.
○ This was done by using the toList() method on line 3.
Challenge: List of Cubes
● You have to create and populate a list of cubes given a list of integers. In
this challenge, you were provided a list of integers and you had to create a
new list of integers which was composed by the cubes of the original list. The
cube of an integer is simply that integer multiplied by itself three times.

● The input is the list integers.


○ Sample input:

● The output will be cubes which should include the cubes of the items in
integers.
○ Sample output:
Unordered Sets
● In Dart, a set is an unordered collection of unique items.
● This means that items do not have a specified position in a set, therefore, a
set cannot have duplicates of the same item.
Creating a Set: Using Literals
● Just like lists, sets can also be created using set literals.
● The syntax is pretty much the same, the only difference is that list literals
use square brackets ([]) while set literals use curly brackets ({}).

● The general syntax is as follows:

○ We start off with the var keyword followed by a unique identifier (setName).

○ After the equals sign (=), we insert the opening curly bracket ({) followed by the
elements we want in our set, with each element being separated by a comma (,).
○ After the last element, we insert the closing curly bracket (}).
Creating a Set: Using Literals
● Let’s look at an example.

● On line 2 of the code snippet above, we are declaring and initializing a set
with three elements.

● When we print the set using the simple print method, the complete set,
with the curly brackets, is displayed.
Creating a Set: Using Literals
● As discussed before, sets don’t have duplicates. However, you can still insert
duplicates when creating a set, but adding a duplicate item has no effect.

● In the code snippet above, we are creating a set with two 3’s.
● However, when we print the set, the second 3 is not displayed.
● This is because Dart ignores the duplicates.
Creating a Set: Using Literals
● If you want to specify the data type during declaration, mention the type
before the opening curly bracket ({) fixed between < >.
Creating a Set: Creating an Empty Set Using a Constructor
● You can also declare a set using a Set constructor.
● A Set constructor creates an object using curly brackets ({}).
● Let’s look at some of the general syntaxes below:

● When declaring an empty set, it is important to mention the data type.


● If we omit the data type, we will end up with a map instead.
Creating a Set: Creating an Empty Set Using a Constructor
● Let’s create a set of fruit.

● When we print setOfFruit and anotherSetOfFruit in the code snippet


above, we get empty sets (curly brackets with no elements).
Working with Sets: Adding a Single Item to a Set
● We can add a single element to an already existing set using the add
method.
○ The only condition is that the item you add must be of the same type as the other
items of the set.

● When called on a set, the add method has a single parameter which is the
item you want to add to a set.
○ The type of the parameter depends on the set you call the method on.

● The general syntax is as follows:


Working with Sets: Adding a Single Item to a Set
● Let’s add some fruits to our set of fruits.

● setOfFruits now contains three elements.


Working with Sets: Adding Multiple Items to a Set
● We can add multiple items to an already existing set using the addAll
method.
○ Again, the only condition is that the items you add must all be of the same type as
the items of the set.
● When called on a set, the addAll method also has a single parameter which
is a set.
○ The set should contain the items you want to add to an already existing set.
○ The type of the parameter is Set<dataType>, where the data type depends on the
set you call the method on.
● In conclusion, addAll basically merges the elements of two sets into one.
● The syntax is as follows:
Working with Sets: Adding Multiple Items to a Set
● Let’s add two more fruits to setOfFruits.

● In the code snippet above, we are adding the items of twoMoreFruits to


setOfFruits.
Working with Sets: Finding the Length of a Set
● Just like lists, sets also have the length property which can be accessed
using the dot operator (.) to give you the number of items in a set.

● The general syntax is as follows.


● Let’s find the length of setOfFruits.

● When you RUN, the number 5 should be displayed because setOfFruits


has five elements.
Working with Sets: Finding the Length of a Set
● Let’s try something. We are going to add a duplicate item to setOfFruits
and see if the length of the set changes.

● When you RUN, the length displayed is still 5, even though it appears that
setOfFruits has 6 items.

● This strengthens our claim that Dart completely ignores duplicate values.
Working with Sets: Removing items from a set
● To remove an item from a set, we can use the remove method which
removes the specified item.

● The remove method has a single parameter which is the item you want to
remove.
○ The type of the parameter depends on the set which the method is being called on.

● The general syntax is as follows:


Working with Sets: Removing items from a set
● Let’s remove some fruits from setOfFruits.

● The final set doesn’t include ‘bananas’.


Working with Sets: Checking a set
● You can check if a set contains specific items using the contains method
and containsAll method depending on if you want to check one item or
multiple items in a set, respectively.

● The general syntax for contains is as follows:

● The general syntax for containsAll is as follows:


Working with Sets: Checking a set
● Let’s look at an example below:

○ When you RUN, the first output displayed should be true because ‘grapes’ is a
part of setOfFruits.

○ The second output you would see printed is false because even though
‘watermelon’ is present in setOfFruits, ‘bananas’ is not.
Working with Sets: Intersection between two sets
● The intersection between two sets (set1, set2) is a set which contains the
elements contained in both set1 and set2.
● The general syntax is as follows
● Let’s look at an example:

● When you RUN, you should see a set with a single item, ‘oranges’.

○ This is because ‘oranges’ is the only item that is contained in both


setOfFruits and SetOfMoreFruits.
Working with Sets: Union between two sets
● The union between two sets (set1, set2) is a set which contains the elements
contained in at least one of the two sets. If an item appears on both sets, it
still only appears once in the union.
● The general syntax is as follows:
● Let’s look at an example:

○ When you RUN, you should see a set with 6 items: apples, oranges,
watermelon, grapes, kiwi, and bananas.
○ This is because these 6 items appear at least once in either
setOfFruits or SetOfMoreFruits..
Maps. Keys and Values
● A map is an unordered collection of key-value pairs.
○ It associates keys and values.

● Every value has a key.


○ This means that every key must be unique, however, the same value can be used
multiple times.

● Two items with the same value will still be unique through their separate
key.

● Use a map when you need to access objects by a unique identifier.


Creating a map: Using literals
● Like lists and sets, maps can also be created using literals.
● The general syntax is as follows:

● The initial syntax is pretty much the same as the syntax for list literals and
set literals.
○ The interesting thing happens after the opening curly bracket ({).
○ Each key-value pair is written one on top of the other.
○ For each pair, the key and value are separated by a colon (:).
○ After the last key-value pair, we move to the next line and insert the closing curly
bracket (}).
Creating a map: Using literals
● We want to create a map
through which we can access
the capital of a country.
● For this example, the key
would be the country and the
value would be its capital.

● The map created above has 7 key-value pairs and when printed, it is
displayed exactly as it was declared; between curly brackets ({}) with each
key-value pair separated with a comma (,) and each key and value
separated by a colon (:).
Creating a map: Using a constructor
● You can also create a map using the Map constructor.
● Its basic syntax is similar to the List constructor.

● Using a constructor results in an empty map.


Creating a map: Specifying the type
● Maps are parameterized types. This means that you can specify what types
the keys and values should be.

● The general syntax is as follows:


● The data type of the keys can be different from that of the values.
● In our example below, the key is of type int and the value is of type String.
Working with Maps: Adding Key-value pairs
● To add a new key-value pair to a map that has already been declared, use the
following syntax:

● Let’s add some key-value pairs to the numbers map we have declared in the
widget below.

● In the code snippet above, we added 3 key-value pairs to numbers.


Working with Maps: Finding the number of pairs in a map
● Just as we discussed for lists and sets, Map has a length property which can
be used to find the number of key-value pairs in a map.

● The general syntax is as follows:


● Let’s find the length of numbers.

● When you press RUN, the number 3 should be displayed because numbers
has three key-value pairs.
Working with Maps: Accessing a value
● By providing a key, you can access its corresponding value using square
brackets ([]).
● The general syntax is as follows:
● Let’s try to access a value from our capitals map from the previous lesson.

● In the code snippet, we want to


retrieve the value associated with the
key Germany. When we print out the
value, Berlin is displayed, which is
the correct value.
● If the key doesn’t exist, you get null
in return.
Working with Maps: Checking a key
● You can check if a map contains a key or not using the containsKey
method.

● The general syntax is as below.

● If the key exists, the method will return true, otherwise it will return false.
Working with Maps: Retrieving all the keys and values
● Map has the keys property and values property which can be used to access
all the keys and values of a particular map.

● The general syntax is as follows:


Working with Maps: Retrieving all the keys and values
● Let’s get all the keys and values of capitals.

● On line 13 of the code snippet above,


we are getting all the keys of capitals
and storing them in allKeys.

● And on line 17, we are getting all the


values of capitals and storing them
in allValues.
Working with Maps: Removing a Key-value pair
● The remove method can be used to remove a key-value pair from a map. The
argument you pass to the method would be the key of the key-value pair you
want to remove from a map.

● The general syntax is as follows:


Working with Maps: Removing a Key-value pair
● Let’s remove a key-value pair from capitals.

● The modified map doesn’t include


'China':'Beijing' anymore.
Control Flow Statements
An Introduction to Control Structures
● Control structures can be thought of
as blocks of code that determine the
flow in which statements (lines of
code) are executed;
○ statements that control the flow of
code (control flow statements).
○ For instance, a block of code can flow
in a sequential manner where a
control structure ensures its
statements are executed sequentially.
○ A block of code can also flow in an
iterative manner where there are
control structures that ensure its
statements are executed iteratively.
Control Flow Statements in Dart
● Dart provides multiple statements that can be used to control the flow of
your Dart code.

● The statements are as follows:


○ if and else

○ for loops

○ while and do-while loops


○ break and continue

○ switch and case


○ assert
The if Statement
● The if statement allows you to incorporate conditions in your code which
need to be fulfilled before the code can execute.

● Conditional statements are incredibly powerful as they take the state of the
program into consideration and act accordingly.

● This provides a decision-making capability to the programmer.


The if Statement: Control flow
● The above flow is showing that if the condition
has been fulfilled, the compiler will execute the
conditional code and if the condition has not
been fulfilled, the compiler will exit that block of
code without executing the conditional code.
The if Statement: Syntax

● The syntax starts with the if keyword followed by parentheses (()).


● In the parentheses, you would write your condition.
● For instance, the condition in our real-life example would be raining outside.
● After the closing parentheses ()), we insert an opening curly bracket ({)
after which we go to the next line and write our conditional code.
● This is code that will execute if the condition holds true.
● After we write the conditional code, we go to the next line and insert the
closing curly bracket (}) and end our if statement.
if in action
● In the example below, we want to empty a list only if it is not empty.
● You can check if a collection is empty using the isEmpty and isNotEmpty
properties.
○ isEmpty is true when a collection is empty and isNotEmpty is true when a
collection is not empty.

○ In the example, the condition is using the


isNotEmpty property to check if testList is
not empty (line 5).

○ If it is not empty, then the conditional code is


executed which first prints “Emptying List”
(line 6) and then clears all the items contained
in testList(line 7).
The else and else if Statement
● Imagine you’re playing a game of basketball. When the game ends, to decide
who won, the referee counts the total points made by each team. If team A
made a greater number of points, they would be declared the winner, else
Team B would be declared the winner.

● Do you see how we have two different actions depending on the outcome?
● If we want to write some code for the above scenario, the first thing that
comes to mind is the if statement.

● But the if statement won’t be able to do the job on its own because it only
caters to one condition and one outcome. Our scenario has two outcomes.
The else Statement
● Dart provides an else statement.
● else is used with an if statement
and tells the compiler what to do if
the if condition is not fulfilled.

● If the condition is not fulfilled, the


compiler executes the alternate
code before exiting.
The else Statement: Syntax
● Let’s take a look at the syntax of an if-else statement.
else in action
● For our example, we are going to write the code for the above basketball
game.
○ The variable pointsA stores the number of points
made by team A and pointsB stores the number of
points made by team B.

○ If team A has a greater number of points than team


B, i.e., pointsA > pointsB, Team A Wins! is printed.
Otherwise, Team B Wins! is printed.

○ Now, what if both teams have the same number of points?


○ The if condition will be false, and the code for else will be executed resulting in an
output of Team B Wins! However, that is incorrect because team B hasn’t won.

○ Let’s see how we can solve this problem in the next slide.
The else if Statement
● else is great when we only have two possible outcomes. However, what
would happen if we have more than two outcomes?

● Dart also provides an else if statement. else if is also used with an if


statement, however, unlike else, you have to specify a condition along with
alternate code which will only execute if the else if condition is true.

● The syntax is as follows:

● else if can also be used with the else statement


The else if Statement
● Let’s solve the problem discussed previously using an else if statement.
○ If team A has a greater number of points than
team B, i.e., (pointsA > pointsB), Team A
Wins! is printed.

○ Otherwise, if team B has a greater number of


points than team A, i.e., (pointsB > pointsA),
Team B Wins! is printed.

○ Finally, if neither team A nor team B has a greater


number of points, by default it’s a tie and It's a
Tie! is printed.
The Ternary Operator
● Dart has an operator that lets you concisely evaluate expressions that might
otherwise require if-else statements.

● The operator that we will be discussing is the ternary operator which is


represented by ?:

● Let’s take a look at how this operator is used.

● If condition is true, expression1 is evaluated and its value is returned.


Otherwise, expression2 is evaluated and its value is returned.
The Ternary Operator
● Let’s look at an example where we have two integers, a and b. If a is greater
than b, we want b to be subtracted from a. Otherwise, we want a to be
subtracted from b.
○ On line 5 we are using the ?: operator.
○ a > b is representing the condition while
a - b is representing the first expression
and b - a is representing the second
expression.

○ The value assigned to a is 5 and the value assigned to b is 2.

○ Hence, a > b is true. As the condition is true, the first expression (a - b)


will be evaluated and its result (3) will be stored in result.
The Ternary Operator
● The previous example could also have been written using an if-else
statement.

● If a and b are equal, the else statement will execute.


Challenge: Pass or Fail
● Given the final percentage a student has gotten at the end of a semester, you need
to write a program that decides if the student has passed or failed the semester.
● If the percentage is higher than or equal to 60, the student has passed the
semester. If the percentage is lower than 60, the student has failed the semester.
● However, the percentage is not the only thing that determines if a student has
passed or failed. A student does not pass if their score is 5 points below the class
average.
● For instance, if the average class score is 70, the student must have a minimum
score of 65 to pass.
● If the average class score is 50, the student still needs a score of 60 to pass based
on our first condition.
Challenge: Pass or Fail
● The input will be the variable percentage which stores the final percentage
the student received.

● The output should be pass if the student has a percentage higher than or
equal to 60 while also being 5 within the average class score, otherwise it
would be fail.
for Loops

● You have to print 100 copies of a document. Imagine having to print each
copy individually and pressing print 100 times.

● It’s a lot more efficient and easier to just tell the printer to print the 100
copies and press print once.

● The printer is performing an operation (printing a document) repeatedly in


a loop until it reaches its goal (100 copies).

● In computer programming, we sometimes come across scenarios where a


block of code needs to be executed multiple times.

● Dart provides for loops for this exact purpose.


for Loops: Control flow

● The for loop allows us to specify a


range of numbers over which we want
our loop to run.

● The iterator is responsible for


keeping track of the iterations.

● Initially, its value is the start of the


loop range and it changes with each
iteration.
for Loops: Syntax
● There is more than one way to write a for loop in Dart.
● Let’s try to generalize the syntax:
○ The syntax starts off with the for keyword which is followed by the iterator. But
how should we define the iterator?

○ The iterator we will be using is a variable that is assigned a range of numbers.

○ You need to specify three things, the initial value or where the range starts, and
the final value, where it ends.

○ You then also need to specify how the iterator will move through the range in
every iteration of the for loop. For instance, it could be incremented by 1 or
decremented by 1.

○ All three things are specified within the parentheses and separated by a
semicolon (;).
for Loop in Action

● Suppose we want to print something five times. We need to specify three


things.
○ The initial value of the iterator: var i = 0 (initial value is 0)
○ The final value of the iterator: i < 5 (up till 5)
○ How the iterator moves through the specified range: i++ (increment by 1)

● Let’s take a look at the code:


○ The print statement is executed five times
with i being sequentially assigned a new
value between 0 and 4 in each iteration.
○ The for expression runs for five iterations.
Iterating through a collection
● We can use for loops to perform some operation on every item in a
collection.

● Let’s print every element in


a list of colors.

○ To create our range for the iterator i, we use the length property.

○ The iterator will stop iterating 1 less than the length of the list.

○ This is because the last index of a list is one less than its length as indexes start
from 0 and length starts from 1.

○ This is why we have written i < colorList.length rather than


i <= colorList.length.
The for-in form
● For sets and lists, you can use the for-in form of iteration.
● The for loop using for-in has the following syntax:
● Let’s use the previous example and modify the code so that it uses the new
form.
○ The code works the same way as the
one we looked at before.

○ However, this time around our range


is the items of a collection.

○ Each item, in turn, is assigned to the iterator i and an operation is performed


on it.

○ In this case, the print method is called for each item.


Conditions with loops
● Up until now, we have been performing the simple print operation. But
there’s a lot more you can perform with loops.

● Let’s incorporate a conditional with a loop.


● In our example, we have a list of integers intList. We only want to print the
even integers from that list.

○ In line 4, we are accessing every item in


the list intList one after the other.

○ On line 5, we are inserting a condition that


an item must be even.
○ Only if the condition is true, will the code
on line 6 be executed.
Challenge: Only Even
● You have to create and populate a list of integers using an already existing
list. Multiply each item in the list with 3. The items of the final list should
only contain even numbers.

● The input is the list integers which you will use to create the array
evenList.

● The output will be the populated evenList.


● Sample input:
● Sample output:
while Loops
● When using the word “while” in a sentence, we relate it to the construct of
time.
○ In English, “while” can be used as a conjunction, indicating the occurrence of one
event while another one is in place.
○ For instance, you can say “I am reading a book while my sister is getting ready”.
○ This sentence is indicating that the event, reading a book, will continue to take
place as long as the event sister is getting ready is in place.

● A while loop in Dart behaves the same way.


● One event is a condition and the other event is a body of code to be executed.
● The body of code will be executed repeatedly again and again as long as the
condition is being fulfilled (holds true).
while Loops: Control flow

● The given flow is showing that if the


condition has been fulfilled, the
compiler will execute the block of code
and check the condition again.

● This loop will occur until the condition


is not fulfilled, in which case the
compiler will exit the block of code.
while Loops: Syntax

● The syntax is pretty straight forward with a while followed by the condition
to be checked in (), which is further followed by curly brackets {}
containing the block of code to be executed if the condition holds true.

● The condition must be an expression of type Boolean.


● If the condition is true, the code will execute.
● If the condition is false, the compiler will exit the code.
while in action

● In the example below, we want to print the numbers from 1 to 10 using a


while loop.
○ The variable count is acting as our loop
control variable.

○ It is initialized with the value 1 and while its


value remains less than or equal to 10 the
block of code in ({}) will keep executing.

○ The block of code is simply printing the


current value of count on line 4 and
incrementing it by one on line 5.
do-while

● Dart also has a do-while loop which works exactly like the while loop with
one added difference, that it executes the block of code before checking the
condition.

● do-while ensures that the code in the curly brackets ({}) will execute at
least once.

● The syntax is as follows:


Learn by example
● Let’s look at a very simple example to understand the subtle difference
between while and do-while.

● The code below declares an immutable variable, alwaysOne, which is


assigned a value of 1.

● We want to print the value of alwaysOne when it is not 1.


● As the condition of alwaysOne != 1 can never be true, the value of
alwaysOne should never be printed.

● But that’s not the case. Let’s run the same code using while and do-while
and see what happens.
While Example

● The only thing printed when the code is


run, is Nothing Happened because the
program never enters the while-loop.
do-while Example

● While the while loop doesn’t execute the


block of code, the do-while loop does as it
checks the condition after block
execution.
Infinite loop
● When declaring a while-loop be careful that the condition does eventually
evaluate to false.

● If it will never evaluate to false and will always be true, the while-loop will
run for an infinite number of iterations resulting in your program to crash.

○ When the program runs, it will eventually


crash.

○ The reason for this is that the condition passed


to while will infinitely remain true.

○ alwaysOne will always be equal to 1 as we never


assign it another value throughout the program.
Challenge: Oven is Ready
● Your oven has an initial temperature and you need to heat it to 375 o. If the
temperature of the oven, upon checking, is under 375 o, you increase the
temp by 25o each time.
○ You need to keep track of the number of times you had to increase the
temperature by 25o.

● The input will be the variable temperature which stores the current
temperature of the oven.
○ You also have a variable count which keeps track of the number of times you
increased the temperature of the oven.

● The output will be the number of times you increased the temperature of
the oven.
The break Statement
● The break is used for prematurely stopping a loop.
● When Dart finds a break statement, it breaks from the loop regardless of
whether the iterations have been completed or not.

● It’s mostly used with a conditional statement.


● Based on the condition, the loop will either need to exit or not.
The break Statement
● Let’s look at an example similar to the one we looked at with for-loops,
where we have a list of integers and we only want to print the even integers
from the list.
○ In this example, however, we only want to know what the first occurrence of an
even integer is.
○ in this example, we have inserted a break
statement in our conditional statement.

○ When the first even integer is found, the


condition of the if statement would become
true, resulting in the execution of line 6 and line
7.

○ On line 7 we are telling the loop to break, so only


the number 6 is printed and not 2 and 4.
The continue Statement
● continue is used to skip the running iteration and move on to the next one,
regardless of if there are still lines of code to be executed.

● Imagine you’re responsible for hiring a new employee for your company
that has 5 years of work experience.
○ You go over the list of candidates.

○ Candidates with less than 5 years of experience are skipped, while candidates with
more than 5 years of experience are called for an interview.

● We will store the experience of our candidates in a list.


○ The first candidate’s experience will be at index 0, the second candidate’s
experience will be at index 1, and so on.
The continue Statement
● Let’s write some Dart code that will be able to tell us which candidate should
be called for an interview.
○ If, on an iteration, the value of
candidateExperience is less than
5, line 7 of the code snippet above
is executed which skips the
current iteration and moves back
to the top of the loop.

○ Hence, the print statement will


never be executed for those
iterations.
switch and case
● The switch statement is a conditional statement similar to if-else.
● It has different case clauses specified by the case keyword which are similar
to conditions in an if-else statement. switch takes an expression and the
case clause which is equivalent to that expression will be executed.

● switch differs from if-else in the fact that if statements can only return
true or false, and can only be defined as such.

● Case clauses, on the other hand, are not restricted to boolean values
(integers, strings, or compile-time constants).

● However, make sure the case clauses have the same type as the expression.
switch and case
● The syntax of switch-case is as follows:

● The expression will be compared with the


caseClause using ==.

● When the caseClause is found, the conditional


code for that particular case is executed, and the
break statement breaks from the switch
statement as only one case can be executed.

● If none of the cases are equal to the expression,


the default clause is executed.
switch and case : Example

● In our example, we have a command. Based on


the value of the command, a statement will be
printed.

● When you run the code snippet, the output will


display open.

● This is because the value of command, which is


passed to switch, has the value OPEN.

● This is handled by the 5th case under which the


conditional code is print('open').
Assertion with assert
● assert is an incredibly useful statement that allows you to put conditions on
code execution.

● It’s used to disrupt normal execution when a boolean condition is false.


● The syntax is as follows:
○ The first argument passed to assert can be any expression that reduces to a
boolean value.

○ If the expression’s value is true, the assertion succeeds, and execution continues.

○ If it’s false, the assertion fails and an exception (error) is thrown.

○ To attach a message to an assertion, add a string as the second argument to


assert.
Assert: Learn by example
● On line 2 of the code snippet above, we are
declaring a variable, variable, without
assigning it a value, hence, it is equivalent to
null.

● On line 5 we are using an assert statement


and passing it the expression variable !=
null.

● As this expression is false, the code after


the assertion will not be executed and an
exception will be thrown.
Assert: Comparing with if
● One thing that might come to mind is that assert is similar to an if
statement.
● Let’s modify the previous code so that it uses an if-else statement rather
than assert.
● For one thing, the program continues to run and
executes until the last line of code.
● Furthermore, using an if statement results in
high levels of nesting of {}'s in code.
● Also, as the code grows and becomes modular, you
can put asserts anywhere in any function as
needed and count on it to disrupt normal
execution when an exceptional condition
arises.
Exploring Functions
Defining a Function
● In this chapter, we will cover user-defined functions and learn how to write
our very own functions.

● The general syntax is as follows:


● Look at an example of a very basic user-defined function.
● The given function is not really of any use
to us as all it does is print the statement
Function Called.

● However, regardless of what a function


does, it follows a general syntax.
Defining a Function: Code explanation
● void is telling us that the function does not return anything.
○ If your function returns something, this is where you would insert its return type,
i.e., int, String, bool, etc.
● Inserting the return type is not required as Dart can use type inference to
infer the return type of the function.
○ However, it is preferred that you insert the return type.
● newPrint is the name of the function in which you get to choose yourself.
○ Make sure the name is meaningful to the functionality of the function.
● newPrint is followed by ().
● The body of the function is wrapped in curly brackets {}.
● print("Function Called"); is the body of the function.
Parameterized functions
● We can create functions that take values just like methods.
○ Parameters are a mechanism to pass values to functions.
○ Let’s create a function that takes two parameters and returns their sum.
○ On line 2, (num x, num y) is telling us that our function
takes two parameters.
■ The first one is named x and must be of type num.
■ The second one is named y and must also be of type
num.
○ Parameters are separated by a comma (,).

○ On line 3, we are returning x+y using the return keyword.


■ The type of the return value of the function must match the return
type of the function.
Syntactic sugar
● A function’s body is encompassed in curly brackets ({}).
○ However, you can choose not to use the curly brackets if the function’s body only
consists of a single expression and write everything in a single line.
● The shorthand syntax is a bit different.

● When using this syntax, you don’t have to use the return keyword to return
a value.
○ The arrow separates the function parameters and function type from the function
body.
○ This method of writing functions is simply syntactic sugar.
○ It does not change the functionality of the function, only its syntax.
Syntactic sugar
● Let’s write our sum function using the shorthand syntax.
Calling a Function
● When you want to use a function, it needs to be invoked by being called
upon.

● You call a user-defined function the same way you call a built-in function; by
calling its name followed by the input in ().

● Let’s call the newPrint function and sum function we defined in the previous
lesson.
Calling a Function
● We will be storing the return value of any
function with a return value in a variable
result.
○ On line 13 of the code snippet above, we are
simply calling the newPrint function which
in return is printing Function Called.

○ On line 16 we are passing 5 and 3 to the


function sum, which will add them together
and return their sum.

○ This sum will then be stored in the variable


result whose value we are printing on line
17.
Calling functions within functions
● Sometimes we come across a situation where the functionality of an already
existing function is required in a new function.
○ Instead of rewriting code, we can simply call the old function in the body of the
new one we are writing.

● Let’s write a function which gives us the square of a given number.


Calling functions within functions
● Now, we want to write a function that takes the sum of the squares of two
numbers.
● Let’s try doing this using the square function
we just defined previously.

● In the given code above, we


are calling the function
square in the function
SquareSum.

● Let’s call SquareSum and


see what happens.
Optional Parameters
● When you want to leave the passing of arguments to functions as an option,
you can use optional parameters.

● A function can have two types of parameters: required and optional.


○ The required parameters are listed first, followed by any optional parameters.

○ Optional parameters can be named or positional.


Named parameters
● In a function, named parameters are declared using curly brackets ({}).

● The optional named parameter is encompassed in curly brackets ({}) within


the parentheses.

● Named parameters are called as such because they need to be named during
a function call.

● Below is the syntax for specifying named parameters during a function call.
Named parameters
● In the example below we are printing a number and two strings.
● The number is a required parameter while the strings are optional named
parameters.
Named parameters
● Let’s call the printer function while only specifying one of the optional
parameters.

● Make sure that the parameter name you are specifying is the same as the
one you have specified as a parameter in the function declaration.
Named parameters
● Now, let’s call printer without specifying any of the optional parameters.

● When we don’t specify an optional parameter, Dart takes it as null.


Named parameters
● Finally, below we are calling printer while specifying all the optional
parameters.
Positional parameters
● Wrapping a set of function’s parameters in square brackets ([]) marks them
as optional parameters.

● The syntax is as follows.


● When calling a function, we pass an optional positional parameter just as we
would a required parameter.
Positional parameters
● In the example below, we have one required parameter and two optional
parameters.

○ In the code snippet above, our return value is different if the optional parameter is
passed during the function call.
○ The purpose of line 3 is to check if the optional parameter has been
specified or not.
Positional parameters
● Let’s call mysteryMessage, and only specify the first optional parameter.
Positional parameters
● Now, let’s call mysteryMessage while specifying both optional parameters.
Positional parameters
● It is important to mention that one of the main differences between
positional and named parameters lies in the fact that you must use
positional parameters in the order they are declared.

● In the previous example, we cannot use where without using what.


● However, this is not the case with named parameters.
Recursive Functions
● Recursive functions are functions that call themselves in their own
function body.

● Recursion is the process of breaking down an expression into smaller and


smaller expressions until you’re able to use the same algorithm to solve
each expression.

● The smaller expressions are similar versions of the original expression.


Recursive Functions
● One way to implement recursive functions is by using an if-else
statement.
● The if represents the base case which is the smallest possible expression on
which an algorithm will run and the else represents the recursive call;
when a function calls itself, it is known as a recursive call.
● The recursive function will keep calling itself in a nested manner without
terminating the call until it is equivalent to the base case in which case the
algorithm will be applied.
● The function calls will move in an outward manner, terminating before
moving on to the next one, reducing themselves until they reach the original
function call.
Factorials
● The implementation of factorials is a very famous recursive problem.
● A factorial of a number is achieved by multiplying all consecutive numbers
starting with 1 until you reach the number in question.

● So, the factorial of 4 (represented as 4!) is equivalent to 1 x 2 x 3 x 4 = 24.


● Recursively, it would look like 4! = 4 x (3!).
Factorials: Dart’s implementation
Factorials: Dart’s implementation
● factorial is a recursive function that takes one parameter; the number
whose factorial is to be calculated.
● The base case is if the number is 1, in which case all we have to do is return 1
as that is its own factorial (lines 2-3).
● We cannot break down the expression further than this, where the factorial
of a number is the number itself.
● However, if the number is not equal to 1, the else expression will be
executed in which the return value is the number being multiplied with the
factorial of the number before it (lines 4-5).
● This will continue until we pass 1 in our recursive call.
Factorials: Dart’s implementation
● Let’s look at a graphical implementation of how this works.

● Do you see how the


result of an inner
function call is used to
terminate its outer
function call?

● Recursion is a difficult concept to wrap your head around, but once you do, it
is an extremely powerful tool you can use in a functional programming
language.
Higher-Order Functions
● Dart is a true object-oriented language,
so even functions are objects and have a
type Function.
○ Functions are treated like first-class
values.
○ What this means is that like any other
value, a function can be assigned to
variables, passed as a parameter to
another function, and can also be
returned as a result.
● Functions that take other functions as
parameters or that return functions as
results are called higher-order
functions.
Higher-Order Functions: Learning by example
● Let’s create a function called forAll which takes a list and another function,
f, as arguments.
○ forAll performs f's functionality on every item in the provided list.
○ forAll returns a new list with the modified elements of the provided list.

○ Since forAll returns a list, we have


specified its return type as List<int>.
○ newList is the list to be returned at the end
of the function.
○ The value of every item in intList is
modified according to the functionality of f
and the modified value is stored in newList
(line 4).
Higher-Order Functions: Learning by example
● We’re going to call forAll in the code
snippet below. The function we will be
passing as an argument will be the
factorial function created in the
previous lesson.

● The first list of integers displayed as


output is the original list provided to
forAll(line 19).

● The second list of integers is the list of


modified elements returned by
forAll(line 20).
The forEach method
● Dart has a built-in method, forEach, which has similar functionality to our
forAll function.

● forEach has a single parameter of type Function and is called on a


collection type.

● The functionality of the function passed to forEach is applied to every item


that forEach is called on.

● However, the function you pass should not have a return value, i.e., it must
be void.
The forEach method
● In the code snippet below, we are passing the built-in print method to
forEach and calling it on a list of integers.

● If we pass our factorial function in place of print in the code snippet


above, we would get an error.
Challenge: Write your First Higher-Order Function
● You need to create a higher-order function,
arithmeticCalculator, which returns the result of an
arithmetic function that has two parameters of type int and
returns a value of type num.
● In this challenge, you will assume that the following
arithmetic functions have been declared:
○ For instance, the arithmeticPrinter will take the add
function as input and return its result.
● arithmeticPrinter has three parameters.
○ A function, f
○ An integer, x
○ An integer, y
● The input will be a function and two integers that will be
passed to the function. Sample input:
● The output will be the result of the arithmetic function.
Sample output:
Nested functions
● Nested functions are functions defined within another function.
● When we create functions within main() we are taking advantage of nested
functions as main() is a function on its own.

● Let’s look at a simple example below.


○ We are declaring a function outerFunction which
is printing the statement Outer Function.

○ The function body of outerFunction also contains


a function declaration for nestedFunction.

○ nestedFunction prints the statement Nested


Function.
Lexical scope
● Lexical scope is the range of functionality of a variable so that it may only be
called from within the block of code in which it is defined.
● Dart is a lexically scoped language, which means that the scope of variables
is determined statically, simply by the layout of the code.
● Each set of curly brackets ({}) acquires its own new scope while inheriting
from the scope in which it was declared.
● With lexical scoping, descendant scopes will access the most recently
declared variable of the same name.
● We know nestedFunction is outside the scope of main(); this was
because it was declared in the scope of outerFunction.
Visibility
● When it comes to what is and isn’t visible in a block of code, there are two
rules.
○ Rule #1: When you define something inside a block of code, it is only visible from
within that block of code.

○ Rule #2: The definitions inside a block of code, shadow definitions of the same
names outside the block of code.
Visibility
● For instance, if we define a variable outside of a function, we can define a
variable with the same name inside the function as well, without it affecting
the outside variable.
● The outer variable will be shadowed by the inner. Let’s look at an example:

● While we are printing a


variable with the same
name, i.e., amIVisible, the
variables are actually
different, hence, we get
two different values in the
output.
Classes
A Brief Introduction to Classes
● Classes are blueprints
● A blueprint is a guide used for making something.
○ In the real world, blueprints are usually plans for making buildings.
○ You can create multiple buildings using the same blueprint with each building
being unique but having the same basic architecture.

○ For instance, a blueprint might specify the number of rooms a house should have.
○ While each house built using that blueprint will have the same number of rooms,
one house might have rooms with white walls and another might have rooms with
blue walls, making them unique entities, but still related through the blueprint.
A Brief Introduction to Classes
● Classes can be thought of as a blueprint with which you can create an object.
● An object is an instance of a class and that instance is the actual thing to be
used in our programs.

● In the same way, a single house is an instance of the blueprint above.


○ The blueprint is just a piece of paper while the house itself is the physical
representation of that blueprint and can actually be lived in.
A Brief Introduction to Classes
● The blueprint will specify the properties the object would have and will also
specify the operations/methods that the object can use.

● The properties and methods of a class are known as the members of that
class.

● Properties in Dart are known as instance variables because they are


variables which are initiated when an object is created, i.e., an instance of a
class.
Class Example
● To make our person class, we first need to define its members, i.e., instance
variables and methods.
○ Every person has a name, a gender, and an age.

○ These are the instance variables of our person class.

● Furthermore, a person can perform certain actions such as ‘walking’ and


‘talking’.
○ These are the methods of our function class.

● When we use our person class to create a person, we will create an instance
of a person with its unique properties.
○ We can create multiple instances using the same class.
Class Example
● Each person, Sarah,
Ben, Martin, and
Hannah can perform
the methods of walking
and talking.
Built-in and user-defined classes
● Classes in Dart are broadly divided into two categories; built-in classes and
user-defined classes.

● When we define a list, we are actually creating an instance, i.e., object, of the
List class.

● This is the case for everything in Dart because it is an object-oriented


programming language.

● Every object is an instance of a class, and all classes descend from the
topmost class in the class hierarchy, the Object class.
Creating a Class in Dart
● To define a class in Dart, the class keyword is used, followed by an
identifier (class name) of your choosing.

● This is followed by the class body which is enclosed by a pair of curly


brackets ({}).

● The class body consists of the members of that class, i.e., instance variables
and methods.
Instance variables
● Our Person class has three instance variables.
● Here’s how you declare instance variables in Dart.

● All uninitialized instance variables have the value null.


Instance methods
● While there are multiple types of methods you can use in a class, this lesson
will only focus on instance methods.

● Instance methods on objects can access instance variables.


● Our methods are walking and talking which will simply print the name of
the person that is walking or talking respectively.

● And with this, we have


created our first class with
three instance variables and
two methods.
Objects of a Class: Instantiating a class
● Once a class has been defined, you can create objects from the class
blueprint using the new keyword followed by a class identifier which is
further followed by parenthesis (()).
Objects of a Class: Instantiating a class
● We usually don’t create objects for the sake of just creating them, rather, we
want to work with them in some way.

● For this reason, we assign the object to a variable. Let’s instantiate our
Person class.
Using class members
● Now that we have our object, firstPerson, let’s learn how to use instance
variables and methods.

● In Dart, we use a dot (.) to refer to an instance variable or method.


Using class members
● If you initialize an instance variable where
it is declared, the value is set when the
instance is created.

● So as soon as firstPerson was created,


the value of age was set as 0.

● Let’s set the value of name and gender


using the dot operator while also
reassigning age a new value.
Using class members
● When you call a method, you invoke it on an
object; the method has access to that object’s
methods and instance variables.
● Let’s call the walking and talking methods and
see what happens.
○ walking() is being invoked on the object
firstPerson and prints a variable name.
○ Since the method is called on an object, it
determines if the variable used is one of the instance
variables of that object.
○ As name is defined for the object firstPerson, the
method will print its value.
○ In the code above, firstPerson.walking() takes
the value of Sarah and prints Sarah is walking.
○ firstPerson.talking() performs a similar
operation, however, prints Sarah is talking
instead.
Multiple objects of the same class
● As classes provide reusable code, it makes
sense that we can create multiple objects
using the same class blueprint.
○ Along with firstPerson, let’s create more
objects of the Person class.
Multiple objects of the same class
● Even though there are multiple name variables, they all are referenced by
different objects, hence, modifying one doesn’t modify the others.

● This is why properties are known as instance variables, because each object
has its own set of those variables.
Constructors
● In Dart, constructors are special functions of a class that are responsible for
initializing the instance variables of that class.

● A constructor must have the same name as the class it is being declared in
and since it is a function, it can be parameterized.
○ However, unlike regular functions, constructors do not have a return value,
hence cannot have a return type.

● Dart offers multiple types of constructors. In this course, we will be learning


about two of them.
○ Generative Constructor

○ Named Constructor
Generative constructor
● The most common form of a constructor, the
generative constructor, creates a new instance
of a class.

● The this keyword refers to the current


instance. On line 8 (this.name = nameC;),
○ we are assigning the value nameC to the instance
variable name of the current instance.

● On line 18, we are creating an instance of the


Person class using the generative constructor.

○ Now instead of individually assigning values to


our instance variables, all we have to do is pass
them to the constructor that will do the rest.
Generative constructor: Syntactic sugar
● A generative constructor doesn’t require
any function body.

● We can assign this.name as a parameter.


This allows us to write concise code.
Named constructor
● We can create multiple constructors in Dart based on different scenarios. In
such cases, it is better to name the constructors for better clarity.

● The general syntax is as follows:


Named constructor
Default constructor
● If you don’t declare a constructor, a default constructor is provided for you.
● A default constructor has zero arguments and creates an instance of a class
without initializing its instance variables.
Getter and Setters
● Getters and setters are special methods that provide read and write access
to an object’s properties.

● Recall how we were able to retrieve and set the values of instance variables
using the dot operator (.).

● Each instance variable has an implicit getter and setter which we have been
using up until now.

● In this lesson, we will explore the getter and setter methods.


Getters
● Getters are functions that are used to retrieve the values of an object’s
properties and are defined using the get keyword.

● The syntax is as follows:


Getters
● Let’s look at a very simple
example of get.

● On line 13, we are creating a


getter function which returns
the value of name of the current
instance.

● On line 21, we are calling the


getter function and the output
should display Sarah.
Setters
● Setters are functions that are used to write the values of an object’s
properties and are defined using the set keyword.

● The syntax is as follows:


Setters
● Let’s expand on the previous
example.

● From line 9 to line 15, we are


creating a setter function which
sets the value for age.
○ The setter has a condition which
makes sure that the user does not
input a negative age.

● On line 23, we are setting the value


of age of firstPerson using the
personAge setter function.
Learning by example
● Let’s look at a slightly more complex problem.
● The class Figure has 4 properties, left, top, width, and height.
○ We are going to create two getter functions which will calculate the value of two
new properties, right and bottom.
● We will also create a setter function for right.
○ The properties right and left are interdependent.
○ This means that based on the value set for right, the value of left needs to be
modified.
○ This is being handled by the setter function.
● Likewise, bottom and height are interdependent.
○ Hence, the setter for bottom modifies the value of height according to the value of
bottom.
Learning by example
● Let’s take a look at the code.
● On line 15, the value of left is 3.
● However, when we call the setter
function right on line 17, the
value of left is modified to -8.
● Which is being displayed on line
18.
Inheritance
● Now that you have been familiarized with objects and classes, let’s talk about
inheritance, one of the core concepts of object-oriented programming.

● Inheritance is a concept through which you can create a new class from an
already existing class.

● The new class inherits the properties (instance variables) and methods of
the existing class.

● The class that inherits the class members is known as the subclass, while
the class that is being inherited from is known as the superclass.
The IS A Relationship
● The next question that might be coming to your mind is when do we use
inheritance?

● Well, the answer is that wherever we come across an IS A relationship


between objects, we can use inheritance.

● In the above illustration, we can see the objects have an IS A relationship


between them.
The IS A Relationship
● The class before is a is the subclass and the class after is a is the superclass.
Extending a Class
● In Dart, we use extends to create a subclass.
● Syntax:
Extending a Class: Implementation
● Let’s look at an example of a vending machine.
○ In a food vending machine, we have several types of products such as beverages,
chocolates, cookies, etc.
■ The noticeable thing here is that we always implement an inheritance
relationship between classes when they have common properties.
■ For example, in the case of products, all the products in a vending machine
have names, prices, expiration dates, etc.
○ Also, the IS A relationship stands valid.
■ A beverage is a product.
■ Chocolate is a product.
■ A cookie is a product.
● So, from the above discussion, we can conclude that if there is a superclass
named Product, we can derive the Beverage, Chocolate, Cookie, etc.
subclasses from the superclass.
Extending a Class: Implementation
● Let’s see how we would code the above classes in Dart.
Extending a Class: Implementation
● The Product class has three instance variables, _name, _price, and _expDate. Product
has a generative constructor and one method that simply prints the properties of the
product.
● On line 15, we are creating the subclass, Beverage, by extending the Product class
using the keyword extends.
● On line 19, we are creating a generative constructor for the Beverage class. To assign
the first three parameters of the Beverage constructor, we are using the Product
constructor. super is used by a subclass to refer to its superclass.
● The beverageDetails() is using the Product method printDetails(), to print the
values of the properties _name, _price, and _expDate. It displays its own properties
itself.
● In the main() function, we are creating an instance of the Beverage class.
Private instance variables
● You might have noticed that we declared all of the instance variables
starting with an underscore (_).

● An underscore ensures that the instance variable is private.


● What this means is that a subclass cannot inherit that particular instance
variable.

● This is why we couldn’t use _name directly in the Beverage class, but we
were able to use printDetails() with ease.
Learn Dart
● Check out the official docs of Dart language, a tour
(https://dart.dev/guides/language/language-tour),

● and their language samples (https://dart.dev/samples).


● Once you have an overview from this Dart tutorial, head over
to http://jpryan.me/dartbyexample/ and do all the examples

You might also like