You are on page 1of 6

Android Development: Lab#2, Introduction of Dart Language

Lab # 2

Introduction of Dart Language


Objective:
To give the basic understanding of the following:

 Introduction of Dart Language


 Variables
 Built in types
 Functions
 Control flow statements
 Exceptions
 Classes

Introduction of Dart Language

Dart is an open-source general-purpose programming language. It is originally developed by Google.


Dart is an object-oriented language with C-style syntax. It supports programming concepts like
interfaces, classes, unlike other programming languages Dart doesn’t support arrays. Dart collections
can be used to replicate data structures such as arrays, generics, and optional typing.

The following code shows a simple Dart program –

void main() {
print("Dart language is easy to learn");
}

LAB INSTRUCTOR:Mohsin Raza Khan 1


Android Development: Lab#2, Introduction of Dart Language

Important concepts

As you learn about the Dart language, keep these facts and concepts in mind:

Everything you can place in a variable is an object, and every object is an instance of a class. Even
numbers, functions, and null are objects. All objects inherit from the Object class.

Unlike Java, Dart doesn’t have the keywords public, protected, and private. If an identifier starts with an
underscore (_), it’s private to its library.

Dart supports top-level functions (such as main()), as well as functions tied to a class or object
(static and instance methods, respectively). You can also create functions within functions (nested or local
functions).

Variables and Data Types

Variable is named storage location and Data types simply refer to the type and size of data associated
with variables and functions.

Dart uses var keyword to declare the variable. The syntax of var is defined below,

Var name = 'Dart';


The final and const keyword is used to declare constants. They are defined as below −
void main() {
final a = 12;
const pi = 3.14;
print(a);
print(pi);
}
Dart language supports the following data types −
 Numbers − It is used to represent numeric literals – Integer and Double.
 Strings − It represents a sequence of characters. String values are specified in either single or
double quotes.
 Booleans − Dart uses the bool keyword to represent Boolean values – true and false.
 Lists and Maps − It is used to represent a collection of objects. A simple List can be defined as
below −.

void main() {
var list = [1,2,3,4,5];
print(list);
}

LAB INSTRUCTOR:Mohsin Raza Khan 2


Android Development: Lab#2, Introduction of Dart Language

The list shown above produces [1,2,3,4,5] list.


Map can be defined as shown here −
void main() {
var mapping = {'id': 1,'name':'Dart'};
print(mapping);
}

 Dynamic − If the variable type is not defined, then its default type is dynamic. The
following example illustrates the dynamic type variable −
void main() {
dynamic name = "Dart";
print(name);
}

Decision making and Loops

A decision making block evaluates a condition before the instructions are executed. Dart
supports If, If...else and switch statements.
Loops are used to repeat a block of code until a specific condition is met. Dart supports for,
for...in, while and do...While loops.
Let us understand a simple example about the usage of control statements and loops −
void main() {
for( var i = 1 ; i <= 10; i++ ) {
if(i%2==0) {
print(i);
}
}
}

LAB INSTRUCTOR:Mohsin Raza Khan 3


Android Development: Lab#2, Introduction of Dart Language

Functions

A function is a group of statements that together performs a specific task. Let us look

void main() {
add(3,4);
}
void add(int a,int b) {
int c;
c = a+b;
print(c);
}

We recommend specifying the types of each function’s arguments and return value:

int fibonacci(int n) {
if (n == 0 || n == 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}

var result = fibonacci(20);

Control Flow Statement

Dart supports the usual control flow statements:

if (year >= 2001) {


print('21st century');
} else if (year >= 1901) {
print('20th century');
}

for (var object in flybyObjects) {


print(object);
}

for (int month = 1; month <= 12; month++) {


print(month);
}

while (year < 2016) {

LAB INSTRUCTOR:Mohsin Raza Khan 4


Android Development: Lab#2, Introduction of Dart Language

year += 1;
}

Exception

To raise an exception, use throw:

if (astronauts == 0) {
throw StateError('No astronauts.');
}

To catch an exception, use a try statement with on or catch (or both):

try {
for (var object in flybyObjects) {
var description = await File('$object.txt').readAsString();
print(description);
}
} on IOException catch (e) {
print('Could not describe object: $e');
} finally {
flybyObjects.clear();
}

Note that the code above is asynchronous; try works for both synchronous code and code in
an async function.

Read more about exceptions, including stack traces, rethrow, and the difference between Error and
Exception.

Classes

Here’s an example of a class with three properties, two constructors, and a method. One of
the properties can’t be set directly, so it’s defined using a getter method (instead of a
variable).

class Spacecraft {
String name;
DateTime launchDate;

// Constructor, with syntactic sugar for assignment to members.


Spacecraft(this.name, this.launchDate) {
// Initialization code goes here.
}

LAB INSTRUCTOR:Mohsin Raza Khan 5


Android Development: Lab#2, Introduction of Dart Language

// Named constructor that forwards to the default one.


Spacecraft.unlaunched(String name) : this(name, null);

int get launchYear =>


launchDate?.year; // read-only non-final property

// Method.
void describe() {
print('Spacecraft: $name');
if (launchDate != null) {
int years =
DateTime.now().difference(launchDate).inDays ~/
365;
print('Launched: $launchYear ($years years ago)');
} else {
print('Unlaunched');
}
}
}

You might use the Spacecraft class like this:

Exercise
1. Find the difference between the square of the sum and the sum of the squares of the first N
natural numbers.

2. Given a number n, determine what the nth prime is. By listing the first six prime numbers: 2,
3, 5, 7, 11, and 13, we can see that the 6th prime is 13.If your language provides methods in
the standard library to deal with prime numbers, pretend they don't exist and implement
them yourself.
3. Reverse a string
 For example: input: "cool" output: "looc"

LAB INSTRUCTOR:Mohsin Raza Khan 6

You might also like