Learn Dart Programming
Contents
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.
|
|
Or simple version
Generally we use this version of main.
|
|
Demo
|
|
1.2 Data Types
Literals in Dart.
|
|
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;
|
|
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
|
|
Print the values
|
|
1.3 String and String Interpolation
Ways to define a String variable
|
|
String Interpolation
|
|
We can interpolate any data type with String in print(...)
using $varname
.
|
|
1.4 Constant and Final Variables
In dart we can create constants using -> final -> const
- final vs const:
final
variable can only be set once and it is initialized when accessedconst
is internally final in nature but it is acompile-time constant
-> i.e. it is initialized during compilation
- Instance variable can be final but cannot be constant
- If you want a Constant class level then make it
static const
.
Demo
|
|
Class level constant
|
|
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
|
|
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
|
|
IF-ELSE ladder
|
|
When the condition is true
the code inside the respective block
gets executed. Otherwise block last
is executed.
Demo
|
|
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
-
condition ? expr1 : expr2;
returnsexpr1
if condition is true else returnsexpr2
1 2 3 4
int a = 12, b = 45; print("Small Number = ${(a < b) ? a : b}"); int c = (a < b) ? a : b; print("Small Number = $c);
-
expr1 ?? expr2
ifexpr1
is not-null, returns its value; otherwise, evaluates and returns the value ofexpr2
1 2 3 4
int x, y = 345; // x = null; print("Value = ${x ?? y}"); int z = x ?? y; 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
|
|
break
is must to stop execution after every case
.
Demo
With integer cases.
|
|
With String cases.
|
|
3. Looping
We can repeat the statements using looping.
There are 3 loops in Dart :
- For
- While
- Do …While
3.1 For loop
- The loop first initializes the
iteration_var
- then checks
breaking_condition
- then executes the
Statements
and - increments or decrements the
iteration_var
and - 2,3,4, are repeated until
breaking_condition
remainstrue
.
Syntax
|
|
Demo
|
|
3.1.1 For … in Loop
Syntax
for(var varname in IterableList){....}
Demo
|
|
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.
|
|
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
|
|
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
|
|
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
|
|
We have already used break
in switch...case
program above.
Continue
continue
is used to skip current iteration.
Demo
|
|
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
|
|
Try doing this and observe the result of i j
.
|
|
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
|
|
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)
|
|
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..
|
|
Copy the above code and run it.
You can also return the string.
|
|
Now, let’s work on our area
example:
|
|
Put this code in your file and call it in the main function as we’ve done in sayHello(...)
function.
Another Example:
|
|
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
|
|
we don’t use the return
keyword here.
So ,
|
|
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.
|
|
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 [ ... ]
.
|
|
4.3.2.2 Optional Named Parameters
we can give the name of parameter while passing the value.
These parameters are surrounded by braces { ... }
.
|
|
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]
.
|
|
Default Named
We pass the default value of the Named Parameter while defining the function {String name = "Dart", int id = 1111}
.
|
|
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.
|
|
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
|
|
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.
|
|
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.
|
|
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.
|
|
5.2.5 Finally Block
This Block is always executed regardless the occurance of the exception.
No exception:
|
|
With Exception:
|
|
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
|
|
Let’s use the custom exception class.
Create a function which throws the exception.
|
|
Now call the function in the try block.
|
|
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.
Author Vikash Patel
LastMod May 12, 2021