Bim30603chapter3 Mobileapplicationprogramming Part2 Dart
Bim30603chapter3 Mobileapplicationprogramming Part2 Dart
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.
● 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.
○ 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.
● 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.
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
● 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.
○ 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.
● 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.
○ 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.
● 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.
● 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.
● 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.
● Then comes the variable’s unique name, followed by an equal sign ( =), and
the initial value.
● 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
○ 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.
○ 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.
2. doubles (double)
● 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.
● 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.
● 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.
● Expressions are evaluated, and the resulting values are converted into
strings and concatenated with the enclosing string.
● The $ sign can be followed by a single identifier id that does not contain the
$ character.
● In the above code, assign a value to the country variable based on the
country you want to visit.
● 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.
● 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.
● Until now, we have been declaring a variable using the following syntax:
● In the code snippet below, we are printing the data type of the variable
bookTitle by calling its property runtimeType.
● 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.
● 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.
● 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.
● 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.
● 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,
● 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.
● 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.
● 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 (=)
● 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.
Multiplicative *, /, /̃, %
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 ..
● 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
● 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.
● 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 (()).
● 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:
● 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 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 removeAt method has a single parameter which is the index of the
element you want to remove.
○ The type of the parameter is int.
● Let’s find the index of ‘carrot’ and remove it from our listOfVegetables.
○ 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 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 ({}).
○ 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 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.
● 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.
○ 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’.
○ 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.
● Two items with the same value will still be unique through their separate
key.
● 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.
● Let’s add some key-value pairs to the numbers map we have declared in the
widget below.
● 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.
● 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.
○ for loops
● Conditional statements are incredibly powerful as they take the state of the
program into consideration and act accordingly.
● 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.
○ 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?
● 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.
○ 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
○ 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.
● The input is the list integers which you will use to create the array
evenList.
● 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.
● 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.
● But that’s not the case. Let’s run the same code using while and do-while
and see what happens.
While Example
● 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.
● 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.
● 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.
● 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:
○ If the expression’s value is true, the assertion succeeds, and execution continues.
● 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.
● 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.
○ 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.
● 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.
● 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.
○ 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:
○ 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.
● The properties and methods of a class are known as the members of that
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.
● 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.
● 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.
● 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.
● 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.
○ Named Constructor
Generative constructor
● The most common form of a constructor, the
generative constructor, creates a new instance
of a class.
● 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.
● 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?
● 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),