Learn Dart Programming

Learn basics of Dart programming language with code examples and explainations.

WORDS: 3657 | CODE BLOCKS: 54 | EXT. LINKS: 1

Good Evening, Here are the Hands-on notes for Dart Programming Language. I created these notes when I was learning Dart Language. So, these notes might help you too. You can use these notes as a quick reference to Syntax and Demo. I’ve covered almost every fundamental concept of Dart in this article.

Photo by Birmingham Museums Trust

1. Basics

1.1 The Main Function

Every Dart program starts execution from main() functions.

The syntax of main function

We use this version when we want to use command line arguments.

dart
1void main(List<String> args){
2    // do your stuff here
3}

Or simple version Generally we use this version of main.

dart
1void main(){
2    // do your stuff here
3}

Demo

dart
 1void main() {
 2  // say hello world
 3  print("Hello World!");
 4  // print some numbers, integer expression
 5  print(1 * 2 + 34 - 12 / 5);
 6  // print double
 7  print(2.53);
 8  // boolean
 9  print(true);
10}

1.2 Data Types

Literals in Dart.

dart
1// literals in Dart
2"Dan"; // String literal
323; // int literal
445.6; // double literal
5true; // bool literal

There are 4 built-in data types in Dart.

SN Data Type Description
1. int Integer value
2. double Floating point value
3. String String value
4. bool true , false value

Syntax creating variables in Dart

Use explicit way to declare the variable.

typename variable_name;

Or initialize while creating. typename variable_name = initial_value;

dart
1int intVariable;
2int anotherIntVariable = 111;
3String name = "Vikas";
4double pi = 3.14;
5bool isdeveloper = true;

Use implicit way to declare the variable.

Use var to create any type of variable. var variable_name;

Or initialize while creating. var variable_name = intial_value;`

Demo

Note: In Dart all the data types are objects and their initial value is null.

Create the variables

dart
 1 // numbers: int
 2  int score = 90;
 3  // store hexadecimal value
 4  int hexValue = 0xEAEAEA;
 5
 6  // numbers: double
 7  double length = 24.6;
 8  double exponentValue = 1.4e5;
 9
10  // String
11  String name = "Dave";
12
13  // boolean
14  bool going = false;
15
16  // use var
17  var name2 = "Vikas"; // String
18  var age = 20;        // int
19  var score2 = 45.6;   // double
20  var isHere = true;   // bool
21  var exp = 2.5e6;     // exponential (double)
22  var hex2 = 0xEC43AB; // hex (int)
23  var data;            // will have null

Print the values

dart
 1print(score);        //int
 2print(hexValue);     //int
 3print(length);       //double
 4print(exponentValue);//double
 5print(going);        //bool
 6print(name);         //String
 7print(name2);        //String
 8print(age);          //int
 9print(score2);       //int
10print(isHere);       //bool
11print(exp);          //double
12print(hex2);         //int
13print(data);         //null value

1.3 String and String Interpolation

Ways to define a String variable

dart
1// ways to define string
2  String s1 = 'Vikas'; // with single quote
3  String s2 = "Dave"; // with double quote
4  String s3 = "It's Easy"; // can use both
5  String s4 = 'It\'s Easy'; // excape sequence
6  String s5 = 'This is a very very long string '
7      'and exceeding the line.'; // long string
8  // auto concatenation of strings

String Interpolation

dart
 1// Normal Concatenation
 2String name = "Vikas";
 3String msg = name + ", We are heading to the west";
 4
 5// Interpolation
 6String msg2 = "$name We are heading to the west";
 7String msglen = "Length of msg = ${msg2.length}";
 8
 9// Print
10print(msg2);
11print(msglen);

We can interpolate any data type with String in print(...) using $varname.

dart
1int BoxLength = 123;
2double BoxWeight = 4522.4545;
3print("Length of box = $BoxLength \nWeight of Box = $BoxWeight");

1.4 Constant and Final Variables

In dart we can create constants using -> final -> const

  1. final vs const:
  • final variable can only be set once and it is initialized when accessed
  • const is internally final in nature but it is a compile-time constant -> i.e. it is initialized during compilation
  1. Instance variable can be final but cannot be constant
  2. If you want a Constant class level then make it static const .

Demo

dart
 1void main() {
 2  // final
 3  final city = "Toronto";
 4  // or
 5  // final String city = "Toronto";
 6  // city = "NY"; // Error: Can't assign to the final variable 'city'.
 7
 8  const PI = 3.1415;
 9  const double gravity = 9.8;
10}

Class level constant

dart
1class Circle {
2  final color = "RED"; // OK
3  // const PI = 3.1415; // Not OK
4  static const PI = 3.1415; // OK
5}

Only static fields can be declared as const. Try declaring the field as final, or adding the keyword static.


2. Control Statements

These statements are use to control the execution flow of the program and add various logics to the program.

2.1 If - Else Statements

Simple condition checking. Syntax

IF alone

dart
1if(condition){
2    // block 1
3    // execute the code
4}

When the condition is true the code inside block 1 gets executed. Otherwise nothing happens to the code inside block 1.

IF and ELSE together

dart
1if(condition){
2    // block 1
3    // execute the code
4} else{
5    // block 2
6    // execute the code
7}

IF-ELSE ladder

dart
 1if(condition){
 2    // block 1
 3    // execute the code
 4} else if(condition2){
 5    // block 2
 6    // execute the code
 7} else if(condition3){
 8    // block 3
 9    // execute the code
10}
11.
12.
13.
14else if(condition n){
15    // block n
16    // execute the code
17} else{
18    // block last
19    // execute the code
20}

When the condition is true the code inside the respective block gets executed. Otherwise block last is executed.

Demo

dart
 1void main() {
 2  var salary = 250000;
 3  if (salary > 200000) {
 4    print("You, can get the Credit Card");
 5  } else if (salary > 150000) {
 6    print("You can apply for the Credit Card");
 7  } else {
 8    print("You cannot get the Credit Card");
 9  }
10}

Check code inside 01 basics/05if_else.dart.


2.2 Conditional Expression

Conditional expression is a simple alternative to if-else. There are two conditional expressions

  1. condition ? expr1 : expr2; returns expr1 if condition is true else returns expr2
dart
1  int a = 12, b = 45;
2   print("Small Number = ${(a < b) ? a : b}");
3   int c = (a < b) ? a : b;
4   print("Small Number = $c);
  1. expr1 ?? expr2 if expr1 is not-null, returns its value; otherwise, evaluates and returns the value of expr2
dart
1  int x, y = 345; // x = null;
2   print("Value = ${x ?? y}");
3   int z = x ?? y;
4   print(z);

2.3 Switch Case

If we have constant conditions like ids as 1, 2, 3, 4, 5 Instead using many if-else statements we can use switch-case statement.

The case can be a constant int or a constant String.

Syntax

dart
 1switch(variable){
 2    case 1:
 3    // code
 4    break; // this is must
 5
 6    case 2:
 7    // another code
 8    break;
 9
10    default:
11    // will execute if no case matches
12}

break is must to stop execution after every case.

Demo

With integer cases.

dart
 1// Integer (int)
 2var option = 2;
 3switch (option) {
 4case 1:
 5    print("Option 1");
 6    break;
 7case 2:
 8    print("Option 2");
 9    break;
10default:
11    print("Invalid option");
12}

With String cases.

dart
 1String name = "Andy";
 2switch (name) {
 3case "Andy":
 4    print("Hello, Andy");
 5    break;
 6case "Dave":
 7    print("Hello, Dave");
 8    break;
 9default:
10    print("No name");
11}

3. Looping

We can repeat the statements using looping. There are 3 loops in Dart :

  • For
  • While
  • Do …While

3.1 For loop

  1. The loop first initializes the iteration_var
  2. then checks breaking_condition
  3. then executes the Statements and
  4. increments or decrements the iteration_var and
  5. 2,3,4, are repeated until breaking_condition remains true.

Syntax

dart
1for(iteration_var; breaking_condition;  increment/decrement)
2{
3    // Statements
4}

Demo

dart
1// print even nums
2for (var i = 1; i <= 10; i++) {
3    if (i % 2 == 0){
4        print(i);
5    }
6}

3.1.1 For … in Loop

Syntax

for(var varname in IterableList){....}

Demo

dart
1// for ..in loop
2List names = ["Dave", "Andy", "Vikas", "Mark"];
3for (var name in names) {
4    print(name);
5}

This loop is very useful when using List and other data containers.

3.1.2 Variation in for

we can omit the initial, breaking and incr/decr statements.

dart
 1for (; x < 20; x++) {
 2    print(x);
 3}
 4
 5for(;;x++){
 6    print(x);
 7    if(x==10){
 8        break;
 9    }
10}
11
12for(var x = 0;;){
13    x++;
14    print(x);
15    if(x==10){
16        break;
17    }
18}

3.2 While Loop

While loop is an entry controlled loop. The code inside {...} of while loop will execute only when the condition is true.

Syntax

while(condition){...}

Here we declare a condition or breaking condition for the loop. See the demo

Demo

dart
1// while loop
2// print 0...9
3var k = 0; // this is must
4while (k < 10) {
5    print(k);
6    k++;
7}

3.3 Do …While Loop

Do …while Loop is an exit controlled loop. Here the Statement will run for the first time regardless the condition is true or false. Then it will check the condition if it is true the the loop will continue execution otherwise it will jump out of the loop.

Syntax

do{...} while(conditon); Here the semicolon(;) is must.

Demo

dart
1// print 0...9
2// do ..while loop
3int x = 0;
4do {
5    print(x);
6    x++;
7} while (x < 10);

While vs Do…While

Both work in similar manner. But, do...while will execute at least once and while won’t.


3.4 Break and Continue

These are two loop control statements. Which are used to forcefully control the flow of loop execution.

Break

break is used to stop the execution, and jump out of the loop.

Demo

dart
 1// break after printing 5
 2for(int i = 0; i < 10; i++){
 3    print(i);
 4    if(i==5){
 5        break;
 6    }
 7}
 8
 9// run and observe
10// break -> stop execution of loop
11for (int i = 0; i < 5; i++) {
12    for (int j = 0; j < 5; j++) {
13        print("$i $j");
14        if (i == 2 && j == 2) {
15            break; // will break inner loop
16        }
17    }
18}

We have already used break in switch...case program above.

Continue

continue is used to skip current iteration.

Demo

dart
1// continue -> skip an iteraion in a loop
2for (var i = 0; i < 10; i++) {
3    if (i == 5) {
4        // skip when i==5
5        continue;
6    }
7    print(i);
8}

3.5 Label

Label is a new concept in Dart (we have seen it in C language with its buddy goto). This is not a magical spell from Hogwarts that will do amazing magical things. It is just a way to make loop more controlled than before. We can name a block of code using label. Take a look at below code snippet.

Demo

dart
 1print("i j");
 2
 3outerLoop:
 4for (int i = 0; i < 5; i++) {
 5  // ignore: unused_label
 6  innerloop:
 7  for (int j = 0; j < 5; j++) {
 8    print("$i $j");
 9    if (i == 2 && j == 2) {
10      break outerLoop; // will break outerloop
11    }
12  }
13}

Try doing this and observe the result of i j.

dart
 1print("i j");
 2
 3outerLoop:
 4for (int i = 0; i < 5; i++) {
 5  // ignore: unused_label
 6  innerloop:
 7  for (int j = 0; j < 5; j++) {
 8    print("$i $j");
 9    if (i == 2 && j == 2) {
10      break innerLoop; // will break innerloop
11    }
12  }
13}

4. Functions

Functions are used to group the code statements that do something. e.g. You want to calculate the area of a rectangle then the formula will be area = length * width. You can do it where you want to use the area. _But, if you want to double the area and add 20 to the result then what ? _ Will you write all the code again and again or find some convenient solution. So, the solution is using functions. Your code will be

dart
1var area = length * width;
2area = area * 2;
3area = area + 20;

Now you are able to use the final value of area. So, let’s declare a simple function that says Hello World! to the user (after learning the simple function we will continue with our area calculation)

dart
1void sayHello(){
2  print("Hello World!");
3  // That's common saying hello to the world
4  // let's say 'Hello Dart, Welcome to Earth'
5  print("Hello Dart, Welcome to Earth");
6}

4.1 Breakdown of function (Syntax)

void : It is the return type as you know Dart is a statically typed language like Java, C++ and C. This tells the compiler that we will return a value of the given type (int, double, String, bool, other user defined types). Here void tells that the function will not return any value. sayHello : It is the name of the function. It can be anything but, should be relevant to the work of the function like: multiplyBy2(), makeHalf(), doubleThevalue(), reduceThree(), calculateSI() etc. () : It is called parameter. we can pass values that we want to work on. Like a name that should be printed instead of Dart or World in the above example. Let’s assume we want to say Hello to you and we don’t know your name then we will pass a String called name and interpolate it with the word Hello and print it. Look at the code below..

dart
 1void sayHello(String name){
 2  print("Hello, $name");
 3
 4}
 5
 6void main(){
 7  sayHello("Vikas"); // Hello, Vikas
 8  sayHello("Dart"); // Hello, Dart
 9  sayHello("World"); // Hello, World
10}

Copy the above code and run it.

You can also return the string.

dart
 1String sayHello(String name){
 2  return "Hello, $name";
 3  // don't forget to change the return type
 4}
 5
 6void main(){
 7  print(sayHello("Vikas")); // Hello, Vikas
 8  print(sayHello("Dart")); // Hello, Dart
 9  print(sayHello("World")); // Hello, World
10}

Now, let’s work on our area example:

dart
1int smartAreaOfRectange(int length, int width) {
2  int area = length * width;
3  area = area * 2;
4  area = area + 20;
5  return area;
6}

Put this code in your file and call it in the main function as we’ve done in sayHello(...) function.

Another Example:

dart
1int doubleIt(int x) {
2  return x * 2 + 17;
3}
4
5void main() {
6  for (int i = 1; i <= 10; i++) {
7    print(doubleIt(i));
8  }
9}

4.2 Function Expression (Fat Arrow =>)

The function expression or Fat Arrow => is used to make the function definition shorter and simpler. It can only be used when there is only one statement in the function. Like , double the value

dart
1int doubleIt(int x) => x*2;

we don’t use the return keyword here. So ,

dart
1int doubleIt(int x) => return x*2;

will be wrong.

4.3 Types of function parameters

PARAMETERS:

  • Required
  • Optional:
    • Positional
    • Named
    • Default:
      • Positional
      • Named

4.3.1 Required Parameters

These are the required parameters that cannot be omitted.

dart
1// required parameters
2void requiredParameters(String c1, String c2, String c3) {
3  print("Required Parameters");
4  print("$c1, $c2, $c3");
5}
6void main() {
7  // required parameters
8  requiredParameters("NY", "Toronto", "San Diego");
9}

4.3.2 Optional Parameters

We can omit passing these parameters. Blank value is considered as null.

4.3.2.1 Optional Positional Parameters

We pass the value based on the portion of the parameter in the function. These parameters are surrounded by brackets [ ... ].

dart
 1// optional positional parameters
 2void optionalPositionalParameters(String c1, String c2, [String c3]) {
 3  print("Optional Positional Parameters");
 4  print("$c1, $c2, $c3");
 5}
 6void main() {
 7  // optional positional parameters
 8  optionalPositionalParameters("NY", "Toronto"); // 2 values
 9  optionalPositionalParameters("NY", "Toronto", "San Diego"); // 3 values
10}

4.3.2.2 Optional Named Parameters

we can give the name of parameter while passing the value. These parameters are surrounded by braces { ... }.

dart
 1// optional named parameters
 2void optionalNamedParameters(String c1, String c2, {String c3}) {
 3  print("Optional Named Parameters");
 4  print("$c1, $c2, $c3");
 5}
 6void main() {
 7  // optional named parameters
 8  optionalNamedParameters("NY", "Toronto");
 9  optionalNamedParameters("NY", "Toronto", c3: "San Diego");
10}

4.3.2.3 Default Parameters

These are the positional and named parameters with default value. Default Positional We pass the default value of the Positional Parameter while defining the function [String name = "Dart", int id = 1111].

dart
 1// default positional parameters
 2void defaultPositionalParameters(String c1, String c2, [String c3 = "Mumbai"]) {
 3  print("deafault positional Parameters");
 4  print("$c1, $c2, $c3");
 5}
 6void main() {
 7  // default positional
 8  defaultPositionalParameters("NY", "Toronto");
 9  defaultPositionalParameters("NY", "Toronto", "San Diego");
10}

Default Named We pass the default value of the Named Parameter while defining the function {String name = "Dart", int id = 1111}.

dart
 1// default named parameters
 2void defaultNamedParameters(String c1, String c2, {String c3 = "Mumbai"}) {
 3  print("default Named Parameters");
 4  print("$c1, $c2, $c3");
 5}
 6
 7void main() {
 8  // default named
 9  defaultNamedParameters("NY", "Toronto");
10  defaultNamedParameters("NY", "Toronto", c3: "San Diego");
11}

5. Exception Handling

What are exceptions ? An Exception is a runtime error which occurs when the program is running due to some error that the compiler was unable to detect. If an exception occurs the program crashes. If not handled may cause serious issues.

Below table showing some exceptions in Dart

S.N. Exception Description
1. DeferredLoadException Thrown when a deferred library fails to load.
2. FormatException Exception thrown when a string or some other data does not have an expected format and cannot be parsed or processed.
3. IntegerDivisionByZeroException Thrown when a number is divided by zero.
4. IOException Base class for all Input-Output related exceptions.
5. IsolateSpawnException Thrown when an isolate cannot be created.
6. Timeout Thrown when a scheduled timeout happens while waiting for an async result.

5.1 Example of Exception

Simplest example will be dividing a number by Zero.

dart
1 void main(){
2    // integer division
3    int result = 12 ~/ 4; // OK
4    int badResult = 15 ~/ 0; // NOT OK
5
6  }

So, the line double badResult = 15 / 0; raises an IntegerDivisionByZeroException exception.

5.2 Handling of Exception

We can handle the exceptions by surrounding the exception occurring code inside a try block. And handle the exception using on, catch, and finally blocks.

5.2.1 Try Block

This is the place where we write an exception occurring statement.

Demo

dart
1try {
2    int answer = 12 ~/ 0;
3    print("Division = $answer");
4}

If the statement inside try block raises an exception the program will not crash this time instead it will throw the exception out of the try block which we’ll have to catch.

5.2.2 On Block

We can use on to catch the exception if we know the thrown exception.

dart
1// CASE1: Handle with "on"
2// use on when we know the exception
3try {
4  int answer = 12 ~/ 0;
5  print("Division = $answer");
6} on IntegerDivisionByZeroException {
7  print("Cannot divide by zero");
8}

Here we know the thrown exception IntegerDivisionByZeroException.

5.2.3 Catch Block

If we don’t know the exception we can simply catch it using catch block.

dart
1// CASE2: Handle with "catch"
2// use catch(e) when we don't know the exception
3try {
4  int answer = 12 ~/ 0;
5  print("Division = $answer");
6} catch (e) {
7  print("The exception : $e");
8}

Here the unknown exception is successfully handled.

5.2.4 Stack Trace

We can use the Stack Trace to find the events that threw the exception.

dart
1// CASE3: using STACK TRACE to know the events occured
2// before exception was thrown
3try {
4  int answer = 12 ~/ 0;
5  print("Division = $answer");
6} catch (e, stackTraceObject) {
7  print("The exception : $e");
8  print("Stack Trace:\n$stackTraceObject");
9}

5.2.5 Finally Block

This Block is always executed regardless the occurance of the exception. No exception:

dart
 1// CASE4: finally clause
 2try {
 3  int answer = 12 ~/ 4;
 4  print("Division = $answer");
 5} catch (e, stackTraceObject) {
 6  print("The exception : $e");
 7  print("Stack Trace:\n$stackTraceObject");
 8} finally {
 9  print("This will always execute No exception)");
10}

With Exception:

dart
 1// CASE4: finally clause
 2try {
 3  int answer = 12 ~/ 0;
 4  print("Division = $answer");
 5} catch (e, stackTraceObject) {
 6  print("The exception : $e");
 7  print("Stack Trace:\n$stackTraceObject");
 8} finally {
 9  print("This will always execute (With exception)");
10}

5.3 Custom Exception

Q. Can we have our iwn exceptions ? A. Yes, we can define our own exception class using the following method.

First create a class with YourCustomExceptionName and implement* the built-in Exception class. Then override the errorMessage() method to display “Your custom error message”.

*We will learn about Object Oriented Programming later in the article.

Demo

dart
1// custom exception class
2class DepositAmountLessThanZeroException implements Exception {
3  String errorMessage() {
4    return "Ammount cannot be less than 0";
5  }
6}

Let’s use the custom exception class. Create a function which throws the exception.

dart
1void depositMoney(int amount) {
2  if (amount < 0) {
3    throw new DepositAmountLessThanZeroException();
4  } else {
5    print("Successful, Deposited $amount");
6  }
7}

Now call the function in the try block.

dart
 1void main() {
 2  // OK
 3  try {
 4    depositMoney(1500);
 5  } catch (e, s) {
 6    print(e.errorMessage());
 7    print(s);
 8  }
 9
10  // OK
11  try {
12    depositMoney(0);
13  } catch (e, s) {
14    print(e.errorMessage());
15    print(s);
16  }
17
18  // Exception
19  try {
20    depositMoney(-1233);
21  } catch (e, s) {
22    print(e.errorMessage());
23    print(s);
24  }
25}

That’s all from my side on basic exception handling. We will discuss the topic in detail later in another blog.

Thanks for reading. 🙏 If you liked it feel free to share with your dear ones.💗 And tell me what do you think in the comment box.💬

Stay tuned.