×

Dart Basics

Dart, as earlier mentioned multiple times, is very similar to C, C++ and Java.

It is an object-oriented, garbage collecting and class-based programming language.

Let’s look further and see what Dart has to offer us.

Introduction to Dart

The best editor recommended learning Dart is Dart Pad, which is available at https://dartpad.dev/.

Dart is like any other IDE (integrated development environment).

  • There is a space for editing the code on the left.
  • There is a run button for running your code.
  • There is a console panel that shows the output.
  • And space where it shows the documentation.

Understanding the concepts

  1. MAIN( )

Main in Dart is very similar to main in any other programming language. It is a pre-defined function, without which the function will not run. The main( ) function is called at the initialisation of a program.

2.   DATA TYPES

Dart language has some of the pre-defined data types. Below is the list of data types that are supported by Dart.

  • Numbers: Number in Dart are regarded as numeric figures. Some data types represent numbers which are- int (which takes integer values only), double (which takes a 64-bit long float digit), and a num (which takes both double and int values). 
  • Strings: This data type only takes characters for input. A string is a pre-defined keyword which represents literals. Syntax-wise, strings are used using double quotes or single quotes.  
  • Booleans: Boolean takes either true or false for input. The keyword for boolean is bool.
  • Lists: the list is another data type that is somewhat close to arrays in C, C++ or other programming languages. The list represents a set of objects in Dart.
  • Maps: The map is also a set of objects like a list. The map works on keys and values. A map is declared in two ways- using map literal and map constructor.

3.    OPERATORS

Operators basically work upon operands. There are several operators Dart uses. Let’s understand each of them separately:

  • Arithmetic Operator: Operator, which takes two operands and performs a mathematical operation on them, is called an arithmetic operator. In dart, we have + (add), - (subtract), * (multiply), / (divide), % (modulo which takes the remainder), ++ (increment), and - - (decrement) to name a few. Arithmetic operators are very essential to our program.
  • Assignment Operator: As the name itself suggests that the assignment operator assigns a certain value to the data types. We have = (simple assignment), += (add and assign), - = (subtract and assign), *= (multiply and assign), and /= (divide and assign) as assignment operators in dart.
  • Bitwise Operator: These kinds of operators are significant to our code. The bitwise operators are used to change individual bits of a number. There are Bitwise AND (&), Bitwise OR ( | ), Bitwise NOT ( ~ ), Left shift (<<), Right shift (>>), and Bitwise XOR ( ^ ) in the case of Dart.
  • Equality Operator: This Operator compares the values of two operands. More particularly, it checks whether the value of two operands given in the code equal or not. There is only one equality operator, which is a double equal sign (==).
  • Logical Operator: These operators logically combine two or more conditions of the operands. There are three logical operators- && (And operator which compares two conditions and then gives the result),  || (Or Operator which also like “And," works on two conditions and even when one condition is true, it will give true as a result), and ! (Not Operator, which reverses the result).
  • Relational Operator: Relational operators draw a comparison between two operands and then gives the output. There are many operators such as greater than ( > ), less than ( < ), greater than or equal to ( >= ), less than or equal to ( <= ), equals to ( = = , which is also an equality operator), and not equal to ( != ). Relational operators give boolean values as output.
  • Short circuit Operator: These operators combine two or more expressions. && and || are two short circuit operators. && only returns true when both the expressions are true but || gives true even when one of the expressions is true. They are very similar to logical operators.
  • Type test Operator: These operators check the type of an object. There are three different types of operators which comes under type test operator.
  1. Is - is Operator gives true when an object has a particular data type.Is ! - it is just the opposite of “is." It gives false as an output when an object has that particular data type.
  • VARIABLES AND FUNCTIONS

Variables in Dart can be defined as explicitly giving a data type in a program. You can declare a datatype with keywords- final and const if you wish to make the value held by a variable constant. Variables can store any kind of data. Var stores any type of data in its memory.

An example of creating a variable is-

var num = 25;
var name = ‘JavaTpoint’;
var isThatTrue = true;

Functions are a set of statements that are used to perform a specific task.

Both functions and variables can be called as the backbone of dart language.

The syntax for creating the name of a function is:

  1. No space between the letters.
  2. The first word should always be a lowercase letter, and consequent words in the name should begin with a capital letter.

For example- addAges( ).

The following is the example of a function:

//Function declaration  
var addAges(num age1, num age2) 
{              
return age1 + age2;  
}  
var num1 = 20;  
var num2= 25;  
var total = addNumbers(num1, num2);

5. HELLO WORLD PROGRAM

Hello world program is an elementary program that shows the basic syntax of dart. Let’s run this program on dart pad.

Dart Basics

6. BASIC SYNTAX

In the above program (hello world). There are many terms that we are not familiar with the case of dart. So, let’s understand each term separately.

  • COMMENTS: In dart, comments are readable explanations in the source code. They are written for the purpose of making source code more understandable to other developers. 
  • main( ): The main function is the heart and soul of every program. It is a pre-defined function that acts as an entry point, where all the programming begins.
  • print( ): The print statement is basically used to print anything the developer wants to print. This function is a pre-defined function that prints a string or a number/value. 
  • Identifiers: identifiers are a set of characters and digits used for naming variables, data types, names of arrays, classes and functions. There are specific rules that needs to be followed while naming an identifier which are:It needs to begin with an alphabet (lowercase or uppercase).It should never begin with a digit.Keywords should never be used as an identifier.In special characters, only underscore “_” and dollar sign “$” is allowed.
  • Keywords: keywords are pre-defined words that carry a special meaning for particular work in code. There are about 48 keywords reserved in dart. Below is the list of every keyword in dart language.
abstractelseimportas
enuminassertexport
interfaceasyncextendsis
awaitextensionlibrarybreak
externalmixincasefactory
newcatch0null
classfinalonconst
finallyoperatorcontinuefor
partcovariantFunctionrethrow
defaultgetreturndeferred
hidesetdoif
showdynamicimplementsStatic

7. OOPS —> classes and objects

Dart is an object-oriented programming language. Concepts such as classes, objects, inheritance, abstraction, polymorphism, and encapsulation are all included in dart programming language.

CLASS IN DART

Class is a user-defined data type that contains data members and data functions. Data members can be defined as data variables, and data functions are the functions that manipulate these variables.

While naming a class, it should not have an underscore, and the name of the class should always start with an uppercase alphabet.

SYNTAX:

class Jobs
{  
String nameOfTheEmployee = “Alex”;
int ageOfTheEmployee = 25;  
}

OBJECTS IN DART

An object can be defined as an instance or a variable of a class. When an object is created, memory is allocated, which has an address associated with it.

SYNTAX:

void main ( )  
{  
var J1 = Jobs( );
var J2 = Jobs( );
print(J1.nameOfTheEmployee);
J2.nameOfTheEmployee = “Jim”;
print(J2.nameOfTheEmployee);  
}

OUTPUT:

Alex Jim

8. LIST AND MAPS

The dart map can be defined as a type of dynamic collection that takes key-value pairs as an input. Those keys and values can be of any type. The specialty of a map is that it can shrink and grow at runtime.

We can declare a map in two ways:

  1. Using map literals: Maps can be declared using the var keyword.

 SYNTAX:

void main( )
{
var sampleMap = {   “employeeNumber” : 12345,   “employeeName” : “Alex”,    “employeePassword” : 123456789,                                  };
print(sampleMap);
}

OUTPUT:

employeeNumber: 12345, employeeName: Alex, employeePassword: 123456789

II.   Using map constructors: while declaring Map using constructors, we use     Map ( ) constructor.

SYNTAX:

void main( )  
{
var job = new Map( );
job[‘employeeName’] = ‘Jim’;
job[‘employeeUniqueID’] = 123456;
print(job);
}  

OUTPUT:

employeeName: Jim, employeeUniqueID: 123456

The list can be defined as an array version of dart programming language. A list is simply an indexable collection of objects put in an orderly manner. Elements in a list have unique index numbers associated with them.

There are mainly two types of lists:

  1. Fixed length list: As the name itself gives away, a fixed-length list has a fixed length associated with it, and it cannot be changed during runtime.

SYNTAX:

void main( )  
{ var size = 3;
var sampleList = new List(3);
sampleList[0] = ‘Alex’;
sampleList[1] = ‘Jim’;
sampleList[2] = ‘John’;
sampleList[3] = ‘Ava’;  
print(sampleList);
}

OUTPUT:

[Alex, Jim, John, Ava]

II.   Growable List: This list is the opposite of the fixed-length list. The growable list can be changed at runtime.  

SYNTAX:

void main( )  
{
var sampleList = [“Alex”, “Jim”, “John”];
print(“Original sample List: $sampleList”);  
sampleList.add(“Ava”);
sampleList.add(“Rita”);
print(sampleList);  
sampleList.remove(“Rita”);
print(sampleList);
}  

OUTPUT:

Original sampleList: [Alex, Jim, John] [Alex, Jim, John, Ava, Rita] [Alex, Jim, John, Ava]

9. LOOPS

Loops are a set of statements that are used to execute some lines of code for a certain number of times in a programming language.

There are two types of loops in dart programming languages. Let’s discuss and understand them in detail.

  1. Definite loop: When the number of iterations in a program are fixed, the loop is called definite loop.
1for loop- This loop reiterates a certain lines of code until the condition is proven false.void main( ) { print(“for loop”); for(int c=1;c<=3;c++)           { print(c);            } }
2for..in loop-void main( ) { var a = [1,2,3,4,5]; print(“for..in loop”); for(var c in a)          { print(c);           } }
  • Indefinite loop: When the number of iterations in a program are not fixed or definite, the loop is called indefinite loop.
1while loop- it executes a set of statement until the condition becomes false.void main( ) { var a = 1; var b = 5; print(“while loop”); while(a<=b)          { print(a); a = a+1;           } }
2do while loop- it executes loop statements and then check the condition for next code line if condition is true.void main( ) { var a = 1; var b = 5; print(“while loop”); do{ print(“do while loop value :${a}”); a = a+1;      } while(a<=b);          }

10. IF, IF-ELSE and SWITCH

if, if-else and switch are an important part of dart programming language.

if and if-else are used to select one option from a set of code.

FOR EXAMPLE:

void main( )
{
var a = 1; var b = 5;
print(“if and if else statements”);  
if(a>b)  
{
print(“a is greater than b”);  
}  
else if(a<b)  
{
print(“a is less than b”);  
}  
else  
{
print(“a and b are equal”);
  }
}

switch is also a conditional statement and is used in form of nested loop.

FOR EXAMPLE:

void main( )
{
var age= 20;
switch(name)  
{
case 1: { print(“age is younger”); } break;
case 2: { print(“age is older”);} break;
case 3: {print(“age is equal”);} break; } }

11. CONTINUE AND BREAK

Continue and break as the name itself suggests, are used to continue the flow of control and end the flow of control respectively.

FOR EXAMPLE:

void main( )
{
var a = 0; while(a<3)      {       a++;      
print(a);     
}
print(“continue and break”);
while(true)
{ a++;
if(a>4)
{
break;
}
if(I==4) {continue;} print(a);
}
}

12. DART FUNCTIONS

Functions in dart are very much the same as functions in any other OOPS programming language. Functions are reusable lines of codes which makes it easier to perform certain tasks.

SYNTAX:

void functionName(String name) { print(name) }

13. DART CONSTRUCTOR AND METHODS

A method in dart can be defined as a set of statements that provide some special behavior to class object. It is a method inside of a class.

SYNTAX:

return_type method_name( ) { //statement }

Constructor is a method that is used to initialize an object of class when it is created.

The name of a constructor should be the same as that of the class.

FOR EXAMPLE:

class Person{ String name;
int age;  
Person(String inputName, int inputAge)
{
name = inputName;
age = inputAge;
}

14. DART LIBRARIES AND PACKAGES

A dart package is a directory that contains metadata and other important aspects of your dart program. A dart package also contains dependencies, functions and classes.

Libraries in dart can be defined as a set of instructions. They are super important in a dart program because it includes a set of classes, constants, functions, typedefs, properties and exceptions.

In order to import a library to your dart code, you need to make changes in pubspec.yaml file that contains dependencies and other metadata. Import your desired library to that file and you are good to go.

15. ASYNC AND AWAIT

Async is short for asynchronous. In dart, we have an option of asynchronous programming. Asynchronous means something not existing at that very time but being there later. When a method is called asynchronous, the rest of the program can continue executing while the asynchronous method is performing its task in the background.

FOR EXAMPLE:

void sampleProgram( )
async
{
print(“let’s understand async better”);
}

await is a keyword that is almost always used in asynchronous programming. await literally means wait until it gives a return value and function is finished.

FOR EXAMPLE:

void main( )
async
{
await sampleProgram( );
print(“you can leave now”);
}

Future is another important type that returns value from an asynchronous function. It either completes with success(.then) or with a failure(.catchError).


Related Topics

Dart Tutorial

Dart is an open-source, structured programming language developed by Google. It is a high-level programming language that emerged in 2011, but its stable version emerged in 2017. It is largely used...

4 minutes read.

Dart Queues

A queue is a user-defined collection of data. It is based on the FIFO principle ( First In First Out ) which implies that the element to be inserted first,...

3 minutes read.

Dart - Control Flow Statements

The control flow statements are used to define the control on the flow of the program. Dart programs are executed in sequential order i.e., the order in which the programming...

1 minute read.

Dart Sets

Sets data type in Dart A set is an unordered collection of items that are unique. Dart infers that sets tale strings as values. Example, var languages = { ‘Dart’ , ‘Flutter’, ‘Python’,...

3 minutes read.

Dart Syntax

In the previous tutorial, we coded our first program in Dart on various platforms understanding the basic functionality of each line of code.  Let us understand the syntax for Dart language...

4 minutes read.

Dart Arithmetic Operators

Arithmetic Operators comprises of all the operators that are used to perform arithmetic operations such as addition, subtraction, multiplication, division, etc. They are binary operators that work upon two operands. Consider A...

2 minutes read.

Golang vs Dart

Go is the procedural programming language. It was founded in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google but was launched in 2009 as the language of...

2 minutes read.

Dart Generators

Synchronous Generator Dart Generator is a unique function that allows us to generate price sequences. Generators return values when needed; means that the value is generated if we try to duplicate...

5 minutes read.

Dart Installation Guide

There are various ways of compiling and running an application created in Dart, either by compiling the Dart code to JavaScript using the Dart2js tool or by running on the...

3 minutes read.

Unit Testing in Dart

Typing testing ensures that your app keeps working as you add more features or change existing functionality. Unit testing helps to confirm the behavior of a single function, method, or...

4 minutes read.

Common Collection Methods

Most of the programming languages have arrays as a way to list items together. However, Dart has a collection of data structures similar to array. These are supported by the...

3 minutes read.

Dart Classes

Dart is an object – oriented programming language that supports all the object-oriented programming concepts such as classes, objects, inheritance, data abstraction and data encapsulation. A class can be defined as...

8 minutes read.

Dart Logical Operators

Logical operators are the operators that combine two or more conditions, and accordingly return a Boolean value : true or false. Assume the value of variable A is 25 and B...

2 minutes read.

Typedef in Dart

In Dart, typedef is used to generate a function type that we can use as a type annotation for declaring variables and return types of the function type. An alias...

4 minutes read.

Dart Miscellaneous Operators

Apart from the operators we studied so far, Dart provides some more operators which are as follows : Conditional OperatorCascade Notations Conditional Operators These are the operators that help in evaluating the expression...

1 minute read.

Dart Numbers

Dart provides an in-built data type ‘Numbers’ that provides two types of values: intdouble 1. int data type int data type supports integer values, and their size or values range is platform-dependent. Integers...

4 minutes read.

Dart Bitwise and Shift Operators

The Bitwise operators are the operators that perform different operations bit by bit on the value of the two operands. List of Bitwise Operators in Dart Sr. Operators Description 1. & ( Binary AND ) It returns...

2 minutes read.

Dart Constants

Dart Constants are the objects or variables whose values can’t change or modify during the execution of the program. Their use case is when we want a particular value to...

2 minutes read.

Dart Operators Precedence and Associativity

Precedence of operators determines the order in which the operators are evaluated if they are grouped together in a sentence. If two operators share an operand then the one with...

5 minutes read.

Dart Basics

Dart, as earlier mentioned multiple times, is very similar to C, C++ and Java. It is an object-oriented, garbage collecting and class-based programming language. Let’s look further and see what Dart has...

10 minutes read.