A conditional/decision-making construct evaluates a condition before the instructions are executed.
Conditional constructs in Dart are classified in the following table.
Sr.No
Statement & Description
1
if statementAn if statement consists of a Boolean expression followed by one or more statements.
2
If…Else StatementAn if can be followed by an optional else block. The else block will execute if the Boolean expression tested by the if block evaluates to false.
3
else…if LadderThe else…if ladder is useful to test multiple conditions. Following is the syntax of the same.
4
switch…case StatementThe switch statement evaluates an expression, matches the expression’s value to a case clause and executes the statements associated with that case.
At times, certain instructions require repeated execution. Loops are an ideal way to do the same. A loop represents a set of instructions that must be repeated. In a loop’s context, a repetition is termed as an iteration.
The following figure illustrates the classification of loops −
Let’s start the discussion with Definite Loops. A loop whose number of iterations are definite/fixed is termed as a definite loop.
Sr.No
Loop & Description
1
for loopThe for loop is an implementation of a definite loop. The for loop executes the code block for a specified number of times. It can be used to iterate over a fixed set of values, such as an array
2
for…in LoopThe for…in loop is used to loop through an object’s properties.
Moving on, let’s now discuss the indefinite loops. An indefinite loop is used when the number of iterations in a loop is indeterminate or unknown. Indefinite loops can be implemented using −
Sr.No
Loop & Description
1
while LoopThe while loop executes the instructions each time the condition specified evaluates to true. In other words, the loop evaluates the condition before the block of code is executed.
2
do…while LoopThe do…while loop is similar to the while loop except that the do…while loop doesn’t evaluate the condition for the first time the loop executes.
Let us now move on and discuss the Loop Control Statements of Dart.
Sr.No
Control Statement & Description
1
break StatementThe break statement is used to take the control out of a construct. Using break in a loop causes the program to exit the loop. Following is an example of the break statement.
2
continue StatementThe continue statement skips the subsequent statements in the current iteration and takes the control back to the beginning of the loop.
Using Labels to Control the Flow
A label is simply an identifier followed by a colon (:) that is applied to a statement or a block of code. A label can be used with break and continue to control the flow more precisely.
Line breaks are not allowed between the ‘continue’ or ‘break’ statement and its label name. Also, there should not be any other statement in between a label name and an associated loop.
Example: Label with Break
void main() {
outerloop: // This is the label name
for (var i = 0; i < 5; i++) {
print("Innerloop: ${i}");
innerloop:
for (var j = 0; j < 5; j++) {
if (j > 3 ) break ;
// Quit the innermost loop
if (i == 2) break innerloop;
// Do the same thing
if (i == 4) break outerloop;
// Quit the outer loop
print("Innerloop: ${j}");
}
}
}
The following output is displayed on successful execution of the above code.
An expression is a special kind of statement that evaluates to a value. Every expression is composed of −
Operands − Represents the data
Operator − Defines how the operands will be processed to produce a value.
Consider the following expression – “2 + 3”. In this expression, 2 and 3 are operands and the symbol “+” (plus) is the operator.
In this chapter, we will discuss the operators that are available in Dart.
Arithmetic Operators
Equality and Relational Operators
Type test Operators
Bitwise Operators
Assignment Operators
Logical Operators
Arithmetic Operators
The following table shows the arithmetic operators supported by Dart.
Sr.No
Operators & Meaning
1
+Add
2
−Subtract
3
-exprUnary minus, also known as negation (reverse the sign of the expression)
4
*Multiply
5
/Divide
6
~/Divide, returning an integer result
7
%Get the remainder of an integer division (modulo)
8
++Increment
9
—Decrement
Equality and Relational Operators
Relational Operators tests or defines the kind of relationship between two entities. Relational operators return a Boolean value i.e. true/ false.
Assume the value of A is 10 and B is 20.
Operator
Description
Example
>
Greater than
(A > B) is False
<
Lesser than
(A < B) is True
>=
Greater than or equal to
(A >= B) is False
<=
Lesser than or equal to
(A <= B) is True
==
Equality
(A==B) is False
!=
Not equal
(A!=B) is True
Type test Operators
These operators are handy for checking types at runtime.
Operator
Meaning
is
True if the object has the specified type
is!
False if the object has the specified type
Bitwise Operators
The following table lists the bitwise operators available in Dart and their role −
Operator
Description
Example
Bitwise AND
a & b
Returns a one in each bit position for which the corresponding bits of both operands are ones.
Bitwise OR
a | b
Returns a one in each bit position for which the corresponding bits of either or both operands are ones.
Bitwise XOR
a ^ b
Returns a one in each bit position for which the corresponding bits of either but not both operands are ones.
Bitwise NOT
~ a
Inverts the bits of its operand.
Left shift
a ≪ b
Shifts a in binary representation b (< 32) bits to the left, shifting in zeroes from the right.
Signpropagating right shift
a ≫ b
Shifts a in binary representation b (< 32) bits to the right, discarding bits shifted off.
Assignment Operators
The following table lists the assignment operators available in Dart.
Sr.No
Operator & Description
1
=(Simple Assignment )Assigns values from the right side operand to the left side operandEx:C = A + B will assign the value of A + B into C
2
??=Assign the value only if the variable is null
3
+=(Add and Assignment)It adds the right operand to the left operand and assigns the result to the left operand.Ex: C += A is equivalent to C = C + A
4
─=(Subtract and Assignment)It subtracts the right operand from the left operand and assigns the result to the left operand.Ex: C -= A is equivalent to C = C – A
5
*=(Multiply and Assignment)It multiplies the right operand with the left operand and assigns the result to the left operand.Ex: C *= A is equivalent to C = C * A
6
/=(Divide and Assignment)It divides the left operand with the right operand and assigns the result to the left operand.
Note − Same logic applies to Bitwise operators, so they will become ≪=, ≫=, ≫=, ≫=, |= and ^=.
Logical Operators
Logical operators are used to combine two or more conditions. Logical operators return a Boolean value. Assume the value of variable A is 10 and B is 20.
Operator
Description
Example
&&
And − The operator returns true only if all the expressions specified return true
(A > 10 && B > 10) is False.
||
OR − The operator returns true if at least one of the expressions specified return true
(A > 10 || B > 10) is True.
!
NOT − The operator returns the inverse of the expression’s result. For E.g.: !(7>5) returns false
!(A > 10) is True.
Conditional Expressions
Dart has two operators that let you evaluate expressions that might otherwise require ifelse statements −
condition ? expr1 : expr2
If condition is true, then the expression evaluates expr1 (and returns its value); otherwise, it evaluates and returns the value of expr2.
expr1 ?? expr2
If expr1 is non-null, returns its value; otherwise, evaluates and returns the value of expr2
Example
The following example shows how you can use conditional expression in Dart −
void main() {
var a = 10;
var res = a > 12 ? "value greater than 10":"value lesser than or equal to 10";
print(res);
}
It will produce the following output −
value lesser than or equal to 10
Example
Let’s take another example −
void main() {
var a = null;
var b = 12;
var res = a ?? b;
print(res);
}
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. There are a LOT of operators provided by elixir. They are divided in the following categories −
Arithmetic operators
Comparison operators
Boolean operators
Misc operators
Arithmetic Operators
The following table shows all the arithmetic operators supported by Elixir language. Assume variable A holds 10 and variable B holds 20, then −
The comparison operators in Elixir are mostly common to those provided in most other languages. The following table sums up comparison operators in Elixir. Assume variable A holds 10 and variable B holds 20, then −
Show Examples
Operator
Description
Example
==
Checks if value on left is equal to value on right(Type casts values if they are not the same type).
A == B will give false
!=
Checks if value on left is not equal to value on right.
A != B will give true
===
Checks if type of value on left equals type of value on right, if yes then check the same for value.
A === B will give false
!==
Same as above but checks for inequality instead of equality.
A !== B will give true
>
Checks if the value of left operand is greater than the value of right operand; if yes, then the condition becomes true.
A > B will give false
<
Checks if the value of left operand is less than the value of right operand; if yes, then the condition becomes true.
A < B will give true
>=
Checks if the value of left operand is greater than or equal to the value of right operand; if yes, then the condition becomes true.
A >= B will give false
<=
Checks if the value of left operand is less than or equal to the value of right operand; if yes, then the condition becomes true.
A <= B will give true
Logical operators
Elixir provides 6 logical operators: and, or, not, &&, || and !. The first three, and or not are strict Boolean operators, meaning that they expect their first argument to be a Boolean. Non Boolean argument will raise an error. While the next three, &&, || and ! are non strict, do not require us to have the first value strictly as a boolean. They work in the same way as their strict counterparts. Assume variable A holds true and variable B holds 20, then −
Checks if both values provided are truthy, if yes then returns the value of second variable. (Logical and).
A and B will give 20
or
Checks if either value provided is truthy. Returns whichever value is truthy. Else returns false. (Logical or).
A or B will give true
not
Unary operator which inverts the value of given input.
not A will give false
&&
Non-strict and. Works same as and but does not expect first argument to be a Boolean.
B && A will give 20
||
Non-strict or. Works same as or but does not expect first argument to be a Boolean.
B || A will give true
!
Non-strict not. Works same as not but does not expect the argument to be a Boolean.
!A will give false
NOTE −and, or, && and || || are short circuit operators. This means that if the first argument of and is false, then it will not further check for the second one. And if the first argument of or is true, then it will not check for the second one. For example,
false and raise("An error")
#This won't raise an error as raise function wont get executed because of short
#circuiting nature of and operator
Bitwise Operators
Bitwise operators work on bits and perform bit by bit operation. Elixir provides bitwise modules as part of the package Bitwise, so in order to use these, you need to use the bitwise module. To use it, enter the following command in your shell −
use Bitwise
Assume A to be 5 and B to be 6 for the following examples −
Show Examples
Operator
Description
Example
&&&
Bitwise and operator copies a bit to result if it exists in both operands.
A &&& B will give 4
|||
Bitwise or operator copies a bit to result if it exists in either operand.
A ||| B will give 7
>>>
Bitwise right shift operator shifts first operand bits to the right by the number specified in second operand.
A >>> B will give 0
<<<
Bitwise left shift operator shifts first operand bits to the left by the number specified in second operand.
A <<< B will give 320
^^^
Bitwise XOR operator copies a bit to result only if it is different on both operands.
A ^^^ B will give 3
~~~
Unary bitwise not inverts the bits on the given number.
~~~A will give -6
Misc Operators
Other than the above operators, Elixir also provides a range of other operators like Concatenation Operator, Match Operator, Pin Operator, Pipe Operator, String Match Operator, Code Point Operator, Capture Operator, Ternary Operator that make it quite a powerful language.
A variable provides us with named storage that our programs can manipulate. Each variable in Elixir has a specific type, which determines the size and layout of the variable’s memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.
Types of Variables
Elixir supports the following basic types of variables.
Integer
These are used for Integers. They are of size 32bit on a 32bit architecture and 64 bits on a 64-bit architecture. Integers are always signed in elixir. If an integer starts to expand in size above its limit, elixir convers it in a Big Integer which takes up memory in range 3 to n words whichever can fit it in memory.
Floats
Floats have a 64-bit precision in elixir. They are also like integers in terms of memory. When defining a float, exponential notation can be used.
Boolean
They can take up 2 values which is either true or false.
Strings
Strings are utf-8 encoded in elixir. They have a strings module which provides a lot of functionality to the programmer to manipulate strings.
Anonymous Functions/Lambdas
These are functions that can be defined and assigned to a variable, which can then be used to call this function.
Collections
There are a lot of collection types available in Elixir. Some of them are Lists, Tuples, Maps, Binaries, etc. These will be discussed in subsequent chapters.
Variable Declaration
A variable declaration tells the interpreter where and how much to create the storage for the variable. Elixir does not allow us to just declare a variable. A variable must be declared and assigned a value at the same time. For example, to create a variable named life and assign it a value 42, we do the following −
life = 42
This will bind the variable life to value 42. If we want to reassign this variable a new value, we can do this by using the same syntax as above, i.e.,
life = "Hello world"
Variable Naming
Naming variables follow a snake_case convention in Elixir, i.e., all variables must start with a lowercase letter, followed by 0 or more letters(both upper and lower case), followed at the end by an optional ‘?’ OR ‘!’.
Variable names can also be started with a leading underscore but that must be used only when ignoring the variable, i.e., that variable will not be used again but is needed to be assigned to something.
Printing Variables
In the interactive shell, variables will print if you just enter the variable name. For example, if you create a variable −
life = 42
And enter ‘life’ in your shell, you’ll get the output as −
42
But if you want to output a variable to the console (When running an external script from a file), you need to provide the variable as input to IO.puts function −
A variable is “a named space in the memory” that stores values. In other words, it acts a container for values in a program. Variable names are called identifiers. Following are the naming rules for an identifier −
Identifiers cannot be keywords.
Identifiers can contain alphabets and numbers.
Identifiers cannot contain spaces and special characters, except the underscore (_) and the dollar ($) sign.
Variable names cannot begin with a number.
Type Syntax
A variable must be declared before it is used. Dart uses the var keyword to achieve the same. The syntax for declaring a variable is as given below −
var name = 'Smith';
All variables in dart store a reference to the value rather than containing the value. The variable called name contains a reference to a String object with a value of “Smith”.
Dart supports type-checking by prefixing the variable name with the data type. Type-checking ensures that a variable holds only data specific to a data type. The syntax for the same is given below −
String name = 'Smith';
int num = 10;
Consider the following example −
void main() {
String name = 1;
}
The above snippet will result in a warning since the value assigned to the variable doesn’t match the variable’s data type.
Output
Warning: A value of type 'String' cannot be assigned to a variable of type 'int'
All uninitialized variables have an initial value of null. This is because Dart considers all values as objects. The following example illustrates the same −
void main() {
int num;
print(num);
}
Output
Null
The dynamic keyword
Variables declared without a static type are implicitly declared as dynamic. Variables can be also declared using the dynamic keyword in place of the var keyword.
The following example illustrates the same.
void main() {
dynamic x = "tom";
print(x);
}
Output
tom
Final and Const
The final and const keyword are used to declare constants. Dart prevents modifying the values of a variable declared using the final or const keyword. These keywords can be used in conjunction with the variable’s data type or instead of the var keyword.
The const keyword is used to represent a compile-time constant. Variables declared using the const keyword are implicitly final.
Syntax: final Keyword
final variable_name
OR
final data_type variable_name
Syntax: const Keyword
const variable_name
OR
const data_type variable_name
Example – final Keyword
void main() {
final val1 = 12;
print(val1);
}
Output
12
Example – const Keyword
void main() {
const pi = 3.14;
const area = pi*12*12;
print("The output is ${area}");
}
The above example declares two constants, pi and area, using the const keyword. The area variable’s value is a compile-time constant.
Output
The output is 452.15999999999997
Note − Only const variables can be used to compute a compile time constant. Compile-time constants are constants whose values will be determined at compile time
Example
Dart throws an exception if an attempt is made to modify variables declared with the final or const keyword. The example given below illustrates the same −
For using any language, you need to understand the basic data types the language supports. In this chapter, we will discuss 7 basic data types supported by the elixir language: integers, floats, Booleans, atoms, strings, lists and tuples.
Numerical Types
Elixir, like any other programming language, supports both integers and floats. If you open your elixir shell and input any integer or float as input, it’ll return its value. For example,
42
When the above program is run, it produces the following result −
42
You can also define numbers in octal, hex and binary bases.
Octal
To define a number in octal base, prefix it with ‘0o’. For example, 0o52 in octal is equivalent to 42 in decimal.
Hexadecimal
To define a number in decimal base, prefix it with ‘0x’. For example, 0xF1 in hex is equivalent to 241 in decimal.
Binary
To define a number in binary base, prefix it with ‘0b’. For example, 0b1101 in binary is equivalent to 13 in decimal.
Elixir supports 64bit double precision for floating point numbers. And they can also be defined using an exponentiation style. For example, 10145230000 can be written as 1.014523e10
Atoms
Atoms are constants whose name is their value. They can be created using the color(:) symbol. For example,
:hello
Booleans
Elixir supports true and false as Booleans. Both these values are in fact attached to atoms :true and :false respectively.
Strings
Strings in Elixir are inserted between double quotes, and they are encoded in UTF-8. They can span multiple lines and contain interpolations. To define a string simply enter it in double quotes −
"Hello world"
To define multiline strings, we use a syntax similar to python with triple double quotes −
"""
Hello
World!
"""
We’ll learn about strings, binaries and char lists(similar to strings) in depth in the strings chapter.
Binaries
Binaries are sequences of bytes enclosed in << >> separated with a comma. For example,
<< 65, 68, 75>>
Binaries are mostly used to handle bits and bytes related data, if you have any. They can, by default, store 0 to 255 in each value. This size limit can be increased by using the size function that says how many bits it should take to store that value. For example,
<<65, 255, 289::size(15)>>
Lists
Elixir uses square brackets to specify a list of values. Values can be of any type. For example,
[1, "Hello", :an_atom, true]
Lists come with inbuilt functions for head and tail of the list named hd and tl which return the head and tail of the list respectively. Sometimes when you create a list, it’ll return a char list. This is because when elixir sees a list of printable ASCII characters, it prints it as a char list. Please note that strings and char lists are not equal. We’ll discuss lists further in later chapters.
Tuples
Elixir uses curly brackets to define tuples. Like lists, tuples can hold any value.
{ 1, "Hello", :an_atom, true
A question arises here, – why provide both lists and tuples when they both work in the same way? Well they have different implementations.
Lists are actually stored as linked lists, so insertions, deletions are very fast in lists.
Tuples on the other hand, are stored in contiguous memory block, which make accessing them faster but adds an additional cost on insertions and deletions.
One of the most fundamental characteristics of a programming language is the set of data types it supports. These are the type of values that can be represented and manipulated in a programming language.
The Dart language supports the following types−
Numbers
Strings
Booleans
Lists
Maps
Numbers
Numbers in Dart are used to represent numeric literals. The Number Dart come in two flavours −
Integer − Integer values represent non-fractional values, i.e., numeric values without a decimal point. For example, the value “10” is an integer. Integer literals are represented using the int keyword.
Double − Dart also supports fractional numeric values i.e. values with decimal points. The Double data type in Dart represents a 64-bit (double-precision) floating-point number. For example, the value “10.10”. The keyword double is used to represent floating point literals.
Strings
Strings represent a sequence of characters. For instance, if you were to store some data like name, address etc. the string data type should be used. A Dart string is a sequence of UTF-16 code units. Runes are used to represent a sequence of UTF-32 code units.
The keyword String is used to represent string literals. String values are embedded in either single or double quotes.
Boolean
The Boolean data type represents Boolean values true and false. Dart uses the bool keyword to represent a Boolean value.
List and Map
The data types list and map are used to represent a collection of objects. A List is an ordered group of objects. The List data type in Dart is synonymous to the concept of an array in other programming languages. The Map data type represents a set of values as key-value pairs. The dart: core library enables creation and manipulation of these collections through the predefined List and Map classes respectively.
The Dynamic Type
Dart is an optionally typed language. If the type of a variable is not explicitly specified, the variable’s type is dynamic. The dynamic keyword can also be used as a type annotation explicitly.
We will start with the customary ‘Hello World’ program.
To start the Elixir interactive shell, enter the following command.
iex
After the shell starts, use the IO.puts function to “put” the string on the console output. Enter the following in your Elixir shell −
IO.puts "Hello world"
In this tutorial, we will use the Elixir script mode where we will keep the Elixir code in a file with the extension .ex. Let us now keep the above code in the test.ex file. In the succeeding step, we will execute it using elixirc−
IO.puts "Hello world"
Let us now try to run the above program as follows −
$elixirc test.ex
The above program generates the following result −
Hello World
Here we are calling a function IO.puts to generate a string to our console as output. This function can also be called the way we do in C, C++, Java, etc., providing arguments in parentheses following the function name −
IO.puts("Hello world")
Comments
Single line comments start with a ‘#’ symbol. There’s no multi-line comment, but you can stack multiple comments. For example −
#This is a comment in Elixir
Line Endings
There are no required line endings like ‘;’ in Elixir. However, we can have multiple statements in the same line, using ‘;’. For example,
IO.puts("Hello"); IO.puts("World!")
The above program generates the following result −
Hello
World!
Identifiers
Identifiers like variables, function names are used to identify a variable, function, etc. In Elixir, you can name your identifiers starting with a lower case alphabet with numbers, underscores and upper case letters thereafter. This naming convention is commonly known as snake_case. For example, following are some valid identifiers in Elixir −
var1 variable_2 one_M0r3_variable
Please note that variables can also be named with a leading underscore. A value that is not meant to be used must be assigned to _ or to a variable starting with underscore −
_some_random_value = 42
Also elixir relies on underscores to make functions private to modules. If you name a function with a leading underscore in a module, and import that module, this function will not be imported.
There are many more intricacies related to function naming in Elixir which we will discuss in coming chapters.
Reserved Words
Following words are reserved and cannot be used as variables, module or function names.
after and catch do inbits inlist nil else end
not or false fn in rescue true when xor
__MODULE__ __FILE__ __DIR__ __ENV__ __CALLER__
Syntax defines a set of rules for writing programs. Every language specification defines its own syntax. A Dart program is composed of −
Variables and Operators
Classes
Functions
Expressions and Programming Constructs
Decision Making and Looping Constructs
Comments
Libraries and Packages
Typedefs
Data structures represented as Collections / Generics
Your First Dart Code
Let us start with the traditional “Hello World” example −
main() {
print("Hello World!");
}
The main() function is a predefined method in Dart. This method acts as the entry point to the application. A Dart script needs the main() method for execution. print() is a predefined function that prints the specified string or value to the standard output i.e. the terminal.
The output of the above code will be −
Hello World!
Execute a Dart Program
You can execute a Dart program in two ways −
Via the terminal
Via the WebStorm IDE
Via the Terminal
To execute a Dart program via the terminal −
Navigate to the path of the current project
Type the following command in the Terminal window
dart file_name.dart
Via the WebStorm IDE
To execute a Dart program via the WebStorm IDE −
Right-click the Dart script file on the IDE. (The file should contain the main() function to enable execution)
Click on the ‘Run <file_name>’ option. A screenshot of the same is given below −
One can alternatively click thebutton or use the shortcut Ctrl+Shift+F10 to execute the Dart Script.
Dart Command-Line Options
Dart command-line options are used to modify Dart Script execution. Common commandline options for Dart include the following −
Sr.No
Command-Line Option & Description
1
-c or –cEnables both assertions and type checks (checked mode).
2
–versionDisplays VM version information.
3
–packages <path>Specifies the path to the package resolution configuration file.
4
-p <path>Specifies where to find imported libraries. This option cannot be used with –packages.
5
-h or –helpDisplays help.
Enabling Checked Mode
Dart programs run in two modes namely −
Checked Mode
Production Mode (Default)
It is recommended to run the Dart VM in checked mode during development and testing, since it adds warnings and errors to aid development and debugging process. The checked mode enforces various checks like type-checking etc. To turn on the checked mode, add the -c or –-checked option before the script-file name while running the script.
However, to ensure performance benefit while running the script, it is recommended to run the script in the production mode.
Consider the following Test.dart script file −
void main() {
int n = "hello";
print(n);
}
Run the script by entering −
dart Test.dart
Though there is a type-mismatch the script executes successfully as the checked mode is turned off. The script will result in the following output −
hello
Now try executing the script with the “- – checked” or the “-c” option −
dart -c Test.dart
Or,
dart - - checked Test.dart
The Dart VM will throw an error stating that there is a type mismatch.
Unhandled exception:
type 'String' is not a subtype of type 'int' of 'n' where
String is from dart:core
int is from dart:core
#0 main (file:///C:/Users/Administrator/Desktop/test.dart:3:9)
#1 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart :261)
#2 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:148)
Identifiers in Dart
Identifiers are names given to elements in a program like variables, functions etc. The rules for identifiers are −
Identifiers can include both, characters and digits. However, the identifier cannot begin with a digit.
Identifiers cannot include special symbols except for underscore (_) or a dollar sign ($).
Identifiers cannot be keywords.
They must be unique.
Identifiers are case-sensitive.
Identifiers cannot contain spaces.
The following tables lists a few examples of valid and invalid identifiers −
Valid identifiers
Invalid identifiers
firstName
Var
first_name
first name
num1
first-name
$result
1number
Keywords in Dart
Keywords have a special meaning in the context of a language. The following table lists some keywords in Dart.
abstract 1
continue
false
new
this
as 1
default
final
null
throw
assert
deferred 1
finally
operator 1
true
async 2
do
for
part 1
try
async* 2
dynamic 1
get 1
rethrow
typedef 1
await 2
else
if
return
var
break
enum
implements 1
set 1
void
case
export 1
import 1
static 1
while
catch
external 1
in
super
with
class
extends
is
switch
yield 2
const
factory 1
library 1
sync* 2
yield* 2
Whitespace and Line Breaks
Dart ignores spaces, tabs, and newlines that appear in programs. You can use spaces, tabs, and newlines freely in your program and you are free to format and indent your programs in a neat and consistent way that makes the code easy to read and understand.
Dart is Case-sensitive
Dart is case-sensitive. This means that Dart differentiates between uppercase and lowercase characters.
Statements end with a Semicolon
Each line of instruction is called a statement. Each dart statement must end with a semicolon (;). A single line can contain multiple statements. However, these statements must be separated by a semicolon.
Comments in Dart
Comments are a way to improve the readability of a program. Comments can be used to include additional information about a program like author of the code, hints about a function/ construct etc. Comments are ignored by the compiler.
Dart supports the following types of comments −
Single-line comments ( // ) − Any text between a “//” and the end of a line is treated as a comment
Multi-line comments (/* */) − These comments may span multiple lines.
Example
// this is single line comment
/* This is a
Multi-line comment
*/
Object-Oriented Programming in Dart
Dart is an Object-Oriented language. Object Orientation is a software development paradigm that follows real-world modelling. Object Orientation considers a program as a collection of objects that communicate with each other via mechanism called methods.
Object − An object is a real-time representation of any entity. As per Grady Brooch, every object must have three features −
State − described by the attributes of an object.
Behavior − describes how the object will act.
Identity − a unique value that distinguishes an object from a set of similar such objects.
Class − A class in terms of OOP is a blueprint for creating objects. A class encapsulates data for the object.
Method − Methods facilitate communication between objects.
Example: Dart and Object Orientation
class TestClass {
void disp() {
print("Hello World");
}
}
void main() {
TestClass c = new TestClass();
c.disp();
}
The above example defines a class TestClass. The class has a method disp(). The method prints the string “Hello World” on the terminal. The new keyword creates an object of the class. The object invokes the method disp().