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

02 Dart Walkthrough

The document provides an outline and overview of key concepts in the Dart programming language, including basic syntax, data types, variables, strings, control flow statements, collections, generics, functions, object-oriented programming concepts like classes and inheritance, and asynchronous programming. It also includes code examples and explanations to demonstrate many of these core Dart language features.
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)
23 views

02 Dart Walkthrough

The document provides an outline and overview of key concepts in the Dart programming language, including basic syntax, data types, variables, strings, control flow statements, collections, generics, functions, object-oriented programming concepts like classes and inheritance, and asynchronous programming. It also includes code examples and explanations to demonstrate many of these core Dart language features.
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/ 71

Dart Language

Walkthrough
Jumail Bin Taliba
School of Computing, UTM
February 2020
Outline
• Introduction to Dart
• Basic syntax
• Identifiers, Data Types, Variables and Naming Convention
• String Interpolation
• Enumeration
• Control Flow Statements
• Collections
• Generics
• Functions
• Object-Oriented Programming
• Asynchronous Programming
References:
https://dart.dev/guides/language/language-tour
Download the source code
1. Open Git Bash
2. Move to the directory where you want to store the code
cd <your_working_directory>
e.g : cd d:/code/dart

3. Download the code from my repository on github to your PC (command


below should be in one-line)
git clone https://github.com/jumail-
utm/dart_walkthrough.git dart_walkthrough

4. Move into the directory


cd dart_walkthrough

5. Open the source code into VS Code (don’t forget the dot)
code .
6. Update (and download) the Dart dependencies (aka packages) for the
project.
• Open Command Palette, Ctrl Shift P
• Choose the menu Pub:Get Packages
Introduction to Dart
• Dart is an open-source, scalable programming language for
building web, server and mobile apps

• Made by Google, Dart 1.0 was released on 2013


• Current version is 2.7 (2020)

• It is purely OOP, dynamic language with C style syntax

• It supports optional static typing and type checks

• Adopts single inheritance with mixins supports

• Influenced by Strongly type languages like Java, C++, C# and


loosely type dynamic language like JavaScript
Basic Dart Program
Variables

Uncommenting Line 6 will give an error. The variable day can


only hold an integer value.
dynamic Types
Output:

1
Monday
var

• Type of day determined by the type of the initializer.


• Uncommenting Line 5 will give an error. day is of type int.
var vs. dynamic

Dart infers the type of day as dynamic. Thus, the variable can
hold any type of value.
const variables

• const variables are compile-time constants


• Cannot be changed at all. Line 3 will produce an error
final variables (1)

• final variables are run-time constants


• Can be set only once. Line 3 will produce an error
final variables (2)

• Line 6 is fine as numbers remains pointing to the same list,


oddNumbers.
• Line 10 will produce an error as we try to change numbers to
another list, evenNumbers
final variables (3)
• Instance variable name
of object p can only be
set once as it is final.

• Line 19 will produce an


error
Constant Variables vs. Constant Values

• Line 5 is fine as oddNumbers remains pointing to the same list.


• Line 6 will produce an error. evenNumbers is pointing to a constant
list.
• oddNumbers and evenNumbers are called constant variables.
• const [2,4] are constant values.
Naming Convention
Functions and variables: Files and directories:
• Camel-case starting with small letter • Lower case
• Each word begins with a capital letter • Words are separated by underscores.

myFirstFunction() my_program.dart
variableName folder
directory_name
User-defined Data Types
• Camel-case starting with Capital letter
• Each word begins with a capital letter

class Person{}
enum DayName{}
String Interpolation

Output:
Student's name: Ali age: 21
Test score: 85.0 Result: Pass
Enumeration
To define named constant values

Output:
[Days.monday, Days.tuesday, Days.wednesday, Days.thursday,
Days.friday, Days.saturday, Days.sunday]
Days.thursday
3
Today, the office is half-day
Control Flow Statements

•If-else
•For loops
•While and do-while
loops
•Break and continue
•Switch and case
If and else
For loops
While and do-while loops
break and continue
Switch and case
Collections

•Lists
•Sets
•Maps
List Collection
A list represents an array
Output:

[10, 20, 30]


The sum is 60
[9, 10, 30, 40]
Set Collection
A set contains unique items
Output:

Set C: {egg} count: 1


Set D: {milk, egg, bread, rice} count: 4
{egg, milk}
{milk, egg, bread, rice}
Map Collection
A map contains items in a form of key and value pairs

Output:
three plus seven is ten
Advanced Operations on Collections

•Collection If
•Collection for
•Spread operator
•High-order methods
Collection if Operations
Conditionally add items to collections

Output:

[Menu, Navigation Bar, Show Random Image, Show network]


Collection for Operations
Add items to collections using loops

Output:

[Ok, Cancel, Add User 1, Add User 2, Add User 9]


Spread operator
Add multiple items into collections

Output:

[ [A, B], D, E, [P, Q, R] ]


[A, B, D, E, P, Q, R]
Function Binding
A variable can hold a function

Output:
10
Closure: () => int from Function 'ten': static.
10
High-order Functions vs Callbacks (1)
• Functions can also be sent as parameters to other
functions.

• These functions are called callback functions

• The receiving functions (or the called functions) are called


high-order functions.

• These are some common characteristics of functional


programming paradigm.
High-order Functions vs Callbacks (2)
• In the following example, functions add, times and substract are
callback functions
• doCalculation is a high-order function

Output:

Result: 3
Result: 20
Result: -3
Lambda Functions
• A callback can be directly written to the high-order function.
• This is called Lambda function (or Anonymous function, i.e. no name)
Collections and High-order Methods (1)
Collections come with several high order methods

Output:
Number 10
Number 1
Number 5
Number 7
Collections and High-order Methods (2)

Output:

Sum = 17
Number odds = 3
Generics (1)
Generics are useful for type safety

Line 5 and 15 will produce errors


Generics (2)
Generics are also useful for reducing code duplication
Without generics: code duplication in two classes
Generics (3)
Generics are also useful for reducing code duplication
Without generics: code duplication in two classes
Generics (4)
Generics are also useful for reducing code duplication
Without generics: code duplication in two classes
Generics (5)
Generics are also useful for reducing code duplication
With generics: reduce code duplication
Functions

•Define functions
•Shorthand
•Function parameters
•Positional parameters
•Named parameters
•Default parameter values
Defining Functions
• Function declaration and definition are in the same place
• Dart supports hoisting. You may write the function call on top of the
function definition

Output:

Rectangle's area is 200.0


Shorthand notations
Use arrow syntax for shorthand. However, applicable only to an
expression.
Function Parameters

• A function can have required and optional parameters.


• The required parameters are listed first, then followed by the
optional.
• An optional parameter can be either a named or positional
parameter.
• A parameter can be specified with a default value
Positional Parameters
Positional parameters are enclosed in [ ]

Output:
Rectangle #1's area is 2.0
Rectangle #2's area is 6.0
Rectangle #3's area is 10.0
Named Parameters
• Named parameters are enclosed in { }
• To make parameters mandatory, annotate them with @required

Output:
Rectangle #1's area is 6.0
Rectangle #2's area is 15.0
Rectangle #3's area is 10.0
Object-Oriented Programming
• Define classes and create
objects
• Abstract Classes
• Constructors
• Inheritances
• Overridden Methods
• Cascade Notations
• Interfaces
• Mixins
Example problem
Abstract Classes
• An abstract class cannot be instantiated.
• It can have methods with or without definition.
Inheritance (1)
• Dart adopts single inheritance model.
• Use the keyword extends.
• Child classes inherit all members from the parent class.
• Child classes can access to parent’s members with super
Inheritance (2)
Overridden Methods
• Override a method if a child class need to have a new version of the
method.
• Annotate each method to be overridden with @override
Creating Objects (1)
• Call to the class constructor when creating objects.
• No need to explicitly write the new operator.
Creating Objects (2)
Output:

Circle's area is 1256.6370614359173


Painted in Yellow

Rectangle's area is 10.0


It is a rectangle
Painted in Green

Square's area is 9.0


It is a rectangle
Painted in White
Cascade Notations
• Cascades are shorthand to make sequence of operations on the
same object in a single statement.
• Use the notation . . (two dots)

This code is equivalent to:


Interface (1)
• Interface allows a class to have method names from other classes
• The class must implement the methods (i.e. re-define the methods)
• Use the keyword implements.
Interface (2)
Interface (3)

Output:
The TV is OFF
The TV is currently turned ON on channel TV3
Switching channel from TV3 to NTV7
The language is set to Bahasa Melayu
Mixin
• Mixin allows adding features to a class.
• Adding features to a class can be done with inheritance.
• So why mixin?

Shark swims

Flying fish swims


and flies

Mutant fish swims,


flies and walks
Solution 1: without inheritance

Problem: Code duplication


Solution 2: Multiple Inheritance

• Solve the problem of code duplication.


• However, multiple inheritance is not supported in Dart
Solution 3: Multi-level Single Inheritance
But what if there is a new class?

Code duplication on the methods fly() and walk()


Solution 4: Mixin to the rescue (1)
• Define classes with mixin
• A mixin class has no declared constructor, no instance, no parent
class and no child classes.
Mixin to the rescue (2)
Mixin to the rescue (3)
• Define the consumer class with the keyword with
• A class can consume multiple mixins.
Mixin to the rescue (4)
Mixin to the rescue (5)
Output:

It is a shark
It swims

It is a flying fish
It swims
It flies

It is a fish
It swims
I believe I can fly
It walks

It is a bird from Bald Eagle species


It flies
It walks
*Asynchronous Programming

•Future
•Async / Await

*This topic will be discussed later

You might also like