Dart tutorial for beginners (Part-1) | Getting started, Data-types

Dart tutorial for beginners (Part-1) | Getting started, Data-types

·

8 min read

Dart is a modern programming language with a similar syntax like most other programming languages designed for client-side development by google and can also use for server-side. Dart can be used to build Mobile Apps, Web Apps, or Server-side Apps. Flutter uses dart for multi-platform development. It is mainly specialized to full needs to create UI.
Compiles to ARM & x64 machine code for mobile, desktop, and backend. Or compile to JavaScript for the web. And with AOT(Ahead Of Time) compiler App compiles to a native app for an instant startup. If you are a mobile developer you know it takes time to reload an App. But with the instant hot reload feature you can instantly reload apps. This is made possible by dart virtual machine's(VM) JIT(Just In Time) compilation.

Getting Started

dartpad is a online code editor for dart. Here you no need to install dart SDK, simply head on to dartpad website and start playing with it.
If you have flutter installed locally, dart SDK comes with it. you can run locally by dart run fileName.dart in the terminal. If you need to install only dart follow the link for a detailed installation guide for any platform.

Screenshot (29).png

Don't ignore comments. I explain most of the features in the comments.
Print hello world to the console.
The entry point of the dart is a main() method. Code inside the main function starts executing when we run the app.

void main(){
    print('Hello world!');
}

output

Hello world!

Comments

// single line comment
/* this is
multi line
comment */

Comments are used for more readability of the code and making the source easier to understand. They are Ignored by Compiler.

More on Print( ) function

void main(){
    int num1 = 3;
    int num2 = 6;
    // prints number
    print(2);
    // prints text
    print('text');
    // use \n for next line
    print('Hello \n programmers')
}

output

2
text
Hello
 programmers

Prints an Object to the console.

Built-in types

Dart is a true object-oriented programming language, so all data-types are objects including function is also object by a type function. Therefore, their initial value is by default 'null'.

  • Numbers
    • int
    • double
  • Strings
  • Booleans
  • Lists ( also known as arrays )
  • Maps
  • Runes
  • Symbols

Numbers

Integers are numbers without a decimal point.
If a number includes a decimal, it is a double. Both int and double are subtypes of num. Instead of int and double we can use num in place.

Note: We can know the type of variable by variableName.runtimeType
Here is some example :

void main(){
// Numbers

// Here number variable is declared with a type int and intialized with a value 1.
int number = 1;
print(number); // Output: 1
// Re-initializing the variable number
number = 3;

print(number); // Output: 3
double decimalNumber = 1.1;

num num1 = 10;
print(num1.runtimeType); // Output: int
num1 = 10.1;
// num1 re-intialized with a value of type double
print(num1.runtimeType); // Output: double

num num2 = 100.5;
print(num2.runtimeType); // Output: double
}

String

The string is used to define text. We can initialize String in 'single quote' or by "double quote".

void main(){
//String
String sentence = 'Hello people';
String languageName = "dart";
}

String Interpolation: It includes variable or expression inside a string literal.

void main(){
String welcome = 'Welcome to $languageName language.';
String sum = 'Sum of 2 and 3 is ${2+3}.';

print(welcome);
print(sum);
}

Output :

Welcome to the dart language.
Sum of 2 and 3 is 5.

Here is an example of using single and double quotes in String literal.
Literals in Dart are the constant values assigned to the variable.

void main(){
String sentence1 = 'Welcome to "dart" language';
String sentence2 = "Welcome to \"dart\" language";
String sentence3 = "It's a dart language";
String sentence4 = 'It\'s a dart language';

print(sentence1);
print(sentence2);
print(sentence3);
print(sentence4);
}

Output:

Welcome to "dart" language
Welcome to "dart" language
It's a dart language
It's a dart language

Boolean
We can initialize the value of variable type bool either with true or false. It can take only these two values.

void main(){
// Booleans
bool isTrue = true;
bool isFalse = false;
}

var
A way to declare variables without specifying its type. A type of variable is determined by its initial value.

void main(){
// Do's
var integer = 1; // type: int
integer = 2; // re-initialized with type int

var boolean = true; // type: bool
boolean = false; // re-initialized with type int

var name = 'JavaScript'; // type: String
name = 'dart'; // re-initialized with type String
// Don't
var number = 1;
print(number.runtimeTpe); // Output: int
// Re-intializing number
number = 'one'; // Error: A value of type 'String' can't be assigned to a variable of type 'int'.

number = 1.1; // Error: A value of type 'double' can't be assigned to a variable of type 'int'.
}

Tip: If you want to declare more than one variable same type(like int) or dynamic type(like var), Example is below:

void main(){
var num1 = 1, language = 'dart', isOOP = true;
int number1 = 1; number2 = 2;
}

Lists

Perhaps the most common collection in nearly every programming language is the array or ordered group of objects. In Dart, arrays are List objects, so most people just call them lists. The list is a group of Objects or also called elements.

Dart list is like JavaScript Arrays. Here's a example:

void main(){
//Lists
var dataTypes = [1, true, "abhi"];
//know the lenght of list by listName.length
print(names.length); // Output: 3
}

Index of first Object is zero, and last Object is listName.length-1. We can access any Object(Every variable in dart is an object) inside the list by providing their index number.

List has two subclasses

  1. Growable list
  2. Fixed-length list
Fixed-length listGrowbale list
Once the length of the list is defined we can not add or remove elements to the list.Length is dynamic. we can modify list length by adding or removing elements.

Fixed-length list

List<int> languages = List.filled(3, 1);

Growable list

// explicitly specifing List type
List<int> number = [1, 2, 4, 5, 6];

  print(number.runtimeType); // List<int>
  //print first Value
  print(number[0]); // Output: 1
  //print last value
  int lastIndex = number.length - 1;
  print(number[lastIndex]); // Output: 5

//Modifying the list

// It adds single value to the end of a list.
number.add(7);
print(number); // [1, 2, 4, 5, 6, 7]

// It adds multiple value to the end of a list.
number.addAll([10, 20]);
print(number); // [1, 2, 4, 5, 6, 7, 10, 20]

// It inserts single value to the mentioned index of a list.
number.insert(2, 3);
print(number); // [1, 2, 4, 5, 6, 7, 10, 20]

// It starts inserting mutiple value from the mentioned index of a list.
number.insertAll(0, [-2, -1, 0]);
print(number); // [-2, -1, 0, 1, 2, 4, 5, 6, 7, 10, 20]

// During insert operation elements start inserting from the mentioned index and later elements will be pushed to last.

// It removes by element value
number.remove(6);
print(number); // [-2, -1, 0, 1, 2, 4, 5, 7, 10, 20]

// It removes by index value
number.removeAt(2);
print(number); // [-2, -1, 1, 2, 4, 5, 7, 10, 20]

// It removes the last value
number.removeLast();
print(number); // [-2, -1, 1, 2, 4, 5, 7, 10]

// It deletes the entire  elements in the list
number.clear();
print(number); // []

Screenshot (28).png

The list still has many methods and properties, explore them by number. in the editor.
Push yourself and explore to get comfortable with the technology.
I do explain a few in later articles.

Sets

A set in Dart is an unordered collection of unique items. It does not contain duplicate elements. Because of this output is not in order as you inserted or initialized. So it does not have index position for elements. Here is a Simple dart set example

var colors = {'red', 'green', 'blue'};

Whenever you use var(var number =1) keyword instead of specifying its types, dart analyzer comes to conclusion based on value initialized(1) and set its data type(int). If you use multiple type(var random={1, true, 'name'}) of elements in collections(List, Set, Map) it uses dynamic type.

// create empty set
Set colors = <String>{}; // or Set<String> colors = {};

//add items to existing set using add() addAll() method.
colors.add('red');
colors.addAll(['green', 'yellow']);
Colors.add('green'); //duplicate entries are ignored because can only store unique elements and length of the set will not be increased
print(colors); // Output {'yellow', 'red', 'green'}
//Use .length to get the number of items in the set
print(colors.length);

//Use contains() method to check exsiting element
print(colors.containe('red')); // true

// Use remove() and removeAll() method to remove existing items
colors.remove('yellow');
colors.removeAll(['red', 'green']);

// Use clear() method to remove all exisiting elements at a time.
colors.clear();

Maps

It's an unordered collection of key-value pairs. Both Keys and values can be any type of object. Keys must be unique shouldn't get repeated, but you can use values multiple times.
Here is the simple example:

var fruits = {'apple': 3, 'banana': 5, 'mango': 5};

// create empty map
// var fruits = Map<String, int>();

// add key value pair to existing Map
fruits['guava'] = 6;

// update
fruits['banana'] = 12;

//print complete map
print(fruits);

//print keys
(print.keys);

// print values
print(fruits.values);

//check whether empty or not
  print(fruits.isEmpty); // false
  print(fruits.isNotEmpty);  // true

//check whether vailable or not
  print(fruits.containsKey('apple')); // true
  print(fruits.containsValue(100)); // false

// know the length of map
  print(fruits.length);

// remove
fruits.remove('apple');
print(fruits); // Output: {guava: 6, banana: 10}

// delete all
fruits.clear(); // Output: {}

If u like the article, bookmark it for future reference.

This is part 1 of the dart tutorial. In the upcoming articles, I'll cover all the topics.