Dart tutorial | flutter dart tutorial for beginners
In this crash course, you will learn the basics of Dart programming, from variables and data types to functions, control flow, and object-oriented programming. By the end of this course, you'll have a solid understanding of the language and be able to build your own applications using Dart and Flutter.
main() function
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. Every app has a main() function.
// top-level function where app execution starts
void main(){
print("Hello World!"); // Print to console
}
Variables in Dart
Variable is used to store the value and refer the memory location in computer memory. When we create a variable, the Dart compiler allocates some space in memory. The size of the memory block of memory is depended upon the type of variable.
int x = 2; // explicitly typed
var p = 5; // type inferred - Generic var with type inference
dynamic z = 8; // variable can take on any type
z = "cool"; // cool
// if you never intend to change a variable use final or const. Something like this:
final email = "test@gmail.com"; // Same as var but cannot be reassigned
final String email = "test@gmail.com"; // you can't change the value
const qty = 5; // Compile-time constant
Datatype in Dart
a data type specifies the type of data that can be stored in a variable. Dart has several built-in data types
int age = 20; // integers, range -2^63 to 2^63 - 1
double height = 1.85; // floating-point numbers
// You can also declare a variable as a num
num x = 1; // x can have both int and double values
num += 2.5;
print(num); //Print: 3.5
String name = "Nicola";
bool isFavourite = true;
bool isLoaded = false;
Comments in Dart
Comments are the set of statements that are ignored by the Dart compiler during the program execution.
// This is a normal, one-line comment.
/// This is a documentation comment, used to document libraries,
/// classes, and their members. Tools like IDEs and dartdoc treat
/// doc comments specially.
/* Comments like these are also supported. */
Operators in Dart
Operators are used to perform mathematical and logical operations on the variables. Each operation in dart uses a symbol called the operator to denote the type of operation it performs.
// Arithmatic Operators
print(2 + 3); //Print: 5
print(2 - 3); //Print: -1
print(2 * 3); //Print: 6
print(5 / 2); //Print: 2.5 - Result is a double
print(5 ~/ 2); //Print: 2 - Result is an int
print(5 % 2); //Print: 1 - Remainder
int a = 1, b;
// Increment
b = ++a; // preIncrement - Increment a before b gets its value.
b = a++; // postIncrement - Increment a AFTER b gets its value.
//Decrement
b = --a; // predecrement - Decrement a before b gets its value.
b = a--; // postdecrement - Decrement a AFTER b gets its value.
//Equality and relational operators
print(2 == 2); //Print: true - Equal
print(2 != 3); //Print: true - Not Equal
print(3 > 2); //Print: true - Grater than
print(2 < 3); //Print: true - Less than
print(3 >= 3); //Print: true - Greater than or equal to
print(2 <= 3); //Print: true - Less than or equal to
// Logical operators
// !expr inverts the expression (changes false to true, and vice versa)
// || logical OR
// && logical AND
bool isOutOfStock = false;
int quantity = 3;
if (!isOutOfStock && (quantity == 2 || quantity == 3)) {
// ...Order the product...
}
Control flow in Dart
Control flow deals with the way instructions are executed in an application. It allows your program to make decisions and perform actions based on those decisions, giving your code more flexibility and power.
// if and else if
if(age < 18){
print("Teen");
} else if( age > 18 && age <60){
print("Adult");
} else {
print("Old");
}
// switch case
enum Pet {dog, cat}
Pet myPet = Pet.dog;
switch(myPet){
case Pet.dog:
print('My Pet is Dog.');
break;
case Pet.cat:
print('My Pet is Cat.');
break;
default:
print('I don\'t have a Pet');
}
// Prints: My Pet is Dog.
// while loop
while (!dreamsAchieved) {
workHard();
}
// do-while loop
do {
workHard();
} while (!dreamsAchieved);
// for loop
for(int i=0; i< 10; i++){
print(i);
}
var numbers = [1,2,3];
// for-in loop for lists
for(var number in numbers){
print(number);
}
Collections in Dart
Collections are groups of objects that represent a particular element
The built-in collection types in Dart include:
List: A List is an ordered collection of objects, where each object is assigned an index. A List can contain objects of any type, including null.
// ordered group of objects
var list = [1, 2, 3];
print(list.length); //Print: 3
print(list[1]); //Print: 2
// other ways of list declaration and initializations
List<String> cities = <String>["New York", "Mumbai", "Tokyo"];
// To create a list that’s a compile-time constant
const constantCities = const ["New York", "Mumbai", "Tokyo"];
Set: A Set is an unordered collection of unique objects. A Set can contain objects of any type, including null.
// A set in Dart is an unordered collection of unique items.
var halogens = {'fluorine', 'chlorine', 'bromine', 'iodine', 'astatine'};
// to create an empty set
var names = <String>{};
Set<String> names = {}; // This works, too.
//var names = {}; // Creates a map, not a set.
Map: A Map is a collection of key-value pairs. The keys and values can be of any type, including null.
// a map is an object that associates keys and values
var person = Map<String, String>();
// To initialize the map, do this:
person['firstName'] = 'Nicola';
person['lastName'] = 'Tesla';
print(person); //Print: {firstName: Nicola, lastName: Tesla}
print(person['lastName']); //Print: Tesla
var nobleGases = {
// Key: Value
2: 'helium',
10: 'neon',
18: 'argon',
};
Functions in Dart
a function is a set of instructions that performs a specific task. Functions can take input parameters, and can return a value or void (no value)
// functions in dart are objects and have a type
int add(int a, int b) {
return a + b;
}
// functions can be assigned to variables
int sum = add(2, 3); // returns: 5
// can be passed as arguments to other functions
int totalSum = add(2, add(2, 3)); // returns : 7
// functions that contain just one expression, you can use a shorthand syntax
// arrow syntax
bool isFav(Product product) => favProductsList.contains(product);
// small one line functions that dont have name
// Anonymous (lambda) functions
int add(a,b) => a+b;
// lambda functions mostly passed as parameter to other functions
const list = ['apples', 'bananas', 'oranges'];
list.forEach(
(item) => print('${list.indexOf(item)}: $item'));
//Prints: 0: apples 1: bananas 2: oranges
Classes & Objects in Dart
a class is a blueprint for creating objects that share common properties and methods. An object is an instance of a class that contains its own state and behavior.
// Class
class Cat {
String name;
// method
void voice() {
print("Meow");
}
}
// object
// instance of a class
// below myCat is Object of class Cat
void main() {
Cat myCat = Cat();
myCat.name = "Kitty";
myCat.voice(); // Prints: Meow
}
// Constructor
class Cat {
String name;
Cat(this.name);
}
void main() {
Cat myCat = Cat("Kitty");
print(myCat.name); // Prints: Kitty
}
// abstract class—a class that can’t be instantiated
// This class is declared abstract and thus can't be instantiated.
abstract class AbstractContainer {
// Define constructors, fields, methods...
void updateChildren(); // Abstract method.
}
// provide read and write access to an object’s properties
class Cat {
String name;
// getter
String get catName {
return name;
}
// setter
void set catName(String name) {
this.name = name;
}
}