Learn Dart Programming In 7 Days - Free Tutorial for Absolute Beginners

Unlock the Secrets of Dart Programming! Learn Dart Programming Language in 7 Days - Free Tutorial for Absolute Beginners. Start Your Coding Journey Today! Master Dart Basics, Syntax, and Concepts Quickly! Dive Into Dart Development with Our Free Step-by-Step Guide.


Learn Dart Programming In 7 Days - Free Tutorial for Absolute Beginners

Dart Basics

1. Introduction to Dart Programming Language

Dart is a programming language created by Google. It's used to build web, mobile, and desktop applications. Imagine it as a tool that helps you tell the computer what to do in a specific way.

Example: Think of Dart as learning a new way to talk to your computer. Just like learning how to write a story, you need to know the words and rules.

2. Dart – SDK Installation

SDK (Software Development Kit) is like a toolbox for Dart. It includes everything you need to write and run Dart programs.

Example: Installing the Dart SDK is like getting a big box of LEGO bricks. Before you can build your LEGO creations (programs), you need to have the bricks (SDK).

3. Steps to Install Dart SDK:

  • Go to the Dart website.
  • Download the SDK for your computer (Windows, Mac, Linux).
  • Follow the instructions to install it.

4. Dart – Comments

Comments are notes in your code that explain what you are doing. They don't affect how the program runs. Our compiler ignores the comments.

Example: Comments are like sticky notes in your book. They help you remember what each part of your code does. 

Syntax:

  • Single-line comment: `//This is a comment`

  • Multi-line comment:  `/*This is a multi-line comment */

Example:
// This is a single-line comment
print('Hello, world!'); /* This is a multi-line comment */

5. Dart - Variables

Variables are used to store data that you can use later in your program.

Example: Think of variables as boxes where you store information. You can label these boxes to know what each one contains.

Syntax:

  • To declare a variable: var variableName;
  • To assign a value to a variable: variableName = value;


Example:
var name = 'John'; // Declares a variable 'name' and assigns it the value 'John'
var age = 10; // Declares a variable 'age' and assigns it the value 10
print(name); // Prints 'John'
print(age); // Prints 10. 


Dart - Operator

Operators are symbols that tell the computer to perform specific mathematical or logical tasks.

Example: Operators are like the tools you use in math, such as +, -, *, and /.

Types Of Operators

1. Arithmetic Operators

These operators are used to perform basic mathematical operations.

  • Addition (+): Adds two values
  • Subtraction (-): Subtracts one value from another
  • Multiplication (*): Multiplies two values
  • Division (/): Divides one value by another, resulting in a double.
  • Integer Division (~/): Divides one value by another, resulting in an integer.
  • Modulus (%): Finds the remainder after division.

2. Comparison Operators

These operators compare two values and return a boolean (true or false).

  • Equal to (==): Checks if two values are equal.
  • Not equal to (!=): Checks if two values are not equal.
  • Greater than (>): Checks if the left value is greater than the right value.
  • Less than (<): Checks if the left value is less than the right value.
  • Greater than or equal to (>=): Checks if the left value is greater than or equal to the right value.
  • Less than or equal to (<=): Checks if the left value is less than or equal to the right value.

3. Logical Operators

These operators are used to combine multiple boolean expressions.

  • Logical AND (&&): Returns true if both expressions are true.
  • Logical OR (||): Returns true if at least one expression is true.
  • Logical NOT (!): Reverses the value of a boolean expression.

4. Assignment Operators

These operators are used to assign values to variables.

  • Assignment (=): Assign the right value to the left variable.
  • Addition assignment (+=): Adds the right value to the left variable and assigns the result to the left variable.
  • Subtraction assignment (-=): Subtracts the right value from the left variable and assigns the result to the left variable.
  • Multiplication assignment (*=): Multiplies the left variable by the right value and assigns the result to the left variable.
  • Division assignment (/=): Divides the left variable by the right value and assigns the result to the left variable.
  • Modulus assignment (%=): Takes the modulus of the left variable by the right value and assigns the result to the left variable.

5. Unary Operators

These operators operate on a single operand.

  • Increment (++): Increases the value of a variable by 1.
  • Decrement (--): Decreases the value of a variable by 1

6. Conditional Operators

These operators are used to evaluate expressions based on a condition.

  • Conditional (? :): Returns one of two values based on a condition.
  • Null-aware (??): Returns the left operand if it is not null; otherwise, it returns the right operand.


Data Types in Dart

In programming, data types are like different kinds of containers that hold specific types of information. Dart is a programming language that uses various data types to store and manipulate data.

1. Dart - Numbers

Numbers in Dart are used to store numerical values. There are two main types: integers (whole numbers) and doubles (decimal numbers).

Example:
int age = 15; // This is an integer
double height = 5.7; // This is a double

Imagine a number line where you have whole numbers like 1, 2, 3, and decimal numbers like 1.5, 2.5. Dart uses these to do math.

2. Dart - Strings

Strings are used to store text. Think of strings like a series of characters inside quotes.

Example:
 String name = "Alice"; // This is a string
String greeting = "Hello, world!"; // Another string 

3. Dart - List

Lists are used to store a collection of items. Imagine a list like a grocery list where you keep adding items.

Example:
List<String> fruits = ["apple", "banana", "cherry"]; // List of fruits
List<int> numbers = [1, 2, 3, 4, 5]; // List of numbers

You can put different items in a list, just like you add different fruits to your shopping list.

4. Dart - Sets

Sets are like lists but they do not allow duplicate items. If you try to add the same item twice, it will only keep one.

Example:
Set<String> animals = {"cat", "dog", "bird"}; // Set of animals

Imagine a set like a unique collection of stamps where no two stamps are the same.

5. Dart - Map

Maps are used to store key-value pairs. Think of a map like a dictionary where you look up a word (key) and find its meaning (value).

Example:
  Map studentAges = {
    "Alice": 15,
    "Bob": 16,
    "Charlie": 17
}; 

You can find the ages of students by their names, like looking up words and their meanings in a dictionary.

6. Queues in Dart

Queues are like lists but items are processed in a specific order: first-in, first-out (FIFO). Imagine a queue like a line of people waiting for ice cream; the first person in line gets served first.

Example:
import 'dart:collection';

Queue<String> queue = Queue();
queue.add("First");
queue.add("Second");
queue.add("Third");

print(queue.removeFirst()); // Outputs: First

The first person in line gets their ice cream first, and then the next person, and so on.

7. Dart - Enums

Enums are used to define a set of named values. Think of enums as a group of related constants.

Example:
 enum Weather { sunny, cloudy, rainy, snowy }

void main() {
    Weather today = Weather.sunny;

    switch (today) {
        case Weather.sunny:
            print("It's a sunny day!");
            break;
        case Weather.cloudy:
            print("It's a cloudy day.");
            break;
        case Weather.rainy:
            print("It's raining.");
            break;
        case Weather.snowy:
            print("It's snowing.");
            break;
    }
}

Enums help you use specific names for things, like different types of weather, making your code easier to understand.

Summary

  • Numbers: Store numerical values (integers and doubles).
  • Strings: Store text.
  • Lists: Store a collection of items.
  • Sets: Store a collection of unique items.
  • Maps: Store key-value pairs like a dictionary.
  • Queues: Process items in a first-in, first-out order.
  • Enums: Define a set of named values for easy reference.

These data types and concepts help you organize and manage different kinds of data in your Dart programs, making it easier to write and understand code.

Control Flow in Dart

1. Dart – If-Else Statements

If-Else Statements allow the program to make decisions based on certain conditions. Think of it like a traffic light system: if the light is green, you go; if it's red, you stop.

Example:
 void main() {
  int score = 85;

  if (score > 50) {
    print('You passed the exam!');
  } else {
    print('You failed the exam.');
  }
}   

This example, if the score is greater than 50, it prints "You passed the exam!" Otherwise, it prints "You failed the exam."

2. Dart – Switch Case Statements

Switch Case Statements are another way to make decisions in your program, useful when you have many conditions to check. Imagine you are checking what day it is and deciding what activity to do.

Example:
void main() {
  String day = 'Monday';

  switch (day) {
    case 'Monday':
      print('Time to go to school.');
      break;
    case 'Saturday':
      print('Time to play!');
      break;
    default:
      print('Just another day.');
  }
}
   

In this example, the program checks the value of the day and prints a message based on it.

3. Dart – Loops

Loops are used to repeat a block of code multiple times. Think of it like running around a track: you keep running until you decide to stop.

Example: While Loop
void main() {
  int count = 1;

  while (count <= 5) {
    print('Lap $count');
    count++;
  }
}

This example prints "Lap 1" to "Lap 5" because it repeats the print statement 5 times.

4. Dart – Loop Control Statements

Loop Control Statements help to control the flow of loops, such as stopping the loop early or skipping an iteration.

Example: Break

 void main() {
  for (int i = 1; i <= 5; i++) {
    if (i == 3) {
      break; // Stop the loop when i is 3
    }
    print('Number $i');
  }
}
  

This example stops the loop when i is 3, so it prints "Number 1" and "Number 2".

Example: Continue
 void main() {
  for (int i = 1; i <= 5; i++) {
    if (i == 3) {
      break; // Stop the loop when i is 3
    }
    print('Number $i');
  }
}
  

This example skips printing "Number 3" but prints all other numbers from 1 to 5.

5. Labels in Dart

Labels in Dart are used to control the flow of nested loops. They allow you to specify which loop to break or continue.

Example:
 void main() {
  for (int i = 1; i <= 5; i++) {
    if (i == 3) {
      break; // Stop the loop when i is 3
    }
    print('Number $i');
  }
}

In this example, the loops print pairs of numbers until i is 2 and j is 2, then it breaks out of both loops.

Dart Key Functions

1. Dart - Function

A function in Dart is a block of code that performs a specific task. You can use functions to organize your code and make it more reusable.

Example:
void sayHello() {
  print('Hello, world!');
}

void main() {
  sayHello(); // This will print 'Hello, world!'
}

In this example, sayHello is a function that prints "Hello, world!". We call this function the main function.

2. Dart – Types of Functions

  1. Named Functions: Standard functions with a name.
  2. Anonymous Functions: Functions without a name, are used for short tasks.
  3. Arrow Functions: Shorthand syntax for functions with a single expression.
  4. Higher-order Functions: Functions that take other functions as parameters or return a function.
  5. Recursive Functions: Functions that call themselves to solve a problem.

Examples of All Types of Functions in single Code
 void main() {
  // Named Function
  int add(int a, int b) {
    return a + b;
  }

  // Anonymous Function
  var list = [1, 2, 3, 4];
  list.forEach((item) {
    print(item); // This will print each item in the list
  });

  // Arrow Function
  int multiply(int a, int b) => a * b;

  // Higher-Order Function
  List doubleNumbers(List list, int Function(int) f) {
    List result = [];
    for (var number in list) {
      result.add(f(number));
    }
    return result;
  }

  List doubled = doubleNumbers(list, (n) => n * 2);
  print(doubled); // This will print [2, 4, 6, 8]

  // Recursive Function
  int factorial(int n) {
    if (n <= 1) return 1;
    return n * factorial(n - 1);
  }

  int result = factorial(5);
  print(result); // This will print 120

  // Using the named function
  int sum = add(3, 5);
  print(sum); // This will print 8

  // Using the arrow function
  int product = multiply(4, 5);
  print(product); // This will print 20
}  


3. Dart – Anonymous Function

An anonymous function, also called a lambda or closure, is a function without a name. It's often used for short, one-time-use functions.

Example:
void main() {
  var list = [1, 2, 3, 4];
  list.forEach((item) {
    print(item);
  });
}

Here, the function passed to forEach is an anonymous function that prints each item in the list.

4 Dart – main() Function

The main() function is the starting point of every Dart program. When you run a Dart program, the main() function is the first function that gets executed.

Example:
void main() {
  print('Program started');
}

This example prints "Program started" when the program runs.

5. Dart – Common Collection Methods

Collections in Dart include lists, sets, and maps. There are several useful methods to work with these collections.

Example:
void main() {
  var list = [1, 2, 3, 4, 5];
  
  // Using the forEach method
  list.forEach((item) {
    print(item);
  });
  
  // Using the map method
  var doubled = list.map((item) => item * 2).toList();
  print(doubled); // This will print [2, 4, 6, 8, 10]
}

In this example, forEach is used to print each item in the list, and the map is used to create a new list with each item doubled.

6. Dart – exit() Function

The exit() function is used to terminate a Dart program immediately. It can be used to stop the program if a certain condition is met.

Example:
import 'dart:io';

void main() {
  print('This will print');
  exit(0); // This will terminate the program
  print('This will not print');
}

Here, exit(0) stops the program, so "This will not print" is never printed.

7. Getter and Setter Methods in Dart

Getters and setters are special methods that provide a way to read and write the properties of an object.

Example:

class Student {
  String _name;

  // Getter
  String get name => _name;

  // Setter
  set name(String value) {
    _name = value;
  }
}

void main() {
  var student = Student();
  student.name = 'Alice'; // Using the setter
  print(student.name); // Using the getter
}

In this example, the name is a property with a getter and setter. We use the setter to set the name and the getter to get the name.

Summary

  • Functions: Blocks of code that perform tasks.
  • Types of Functions: Named functions and anonymous functions.
  • Anonymous Function: A function without a name, often used for short tasks.
  • main() Function: The starting point of every Dart program.
  • Common Collection Methods: Methods like forEach and map are used to work with lists.
  • exit() Function: Terminates the program immediately.
  • Getters and Setters: Methods to read and write properties of an object.

Object-Oriented Programming (OOPS) in Dart

Object-Oriented Programming (OOP) in Dart is a way to structure your code using objects and classes. It makes your code more modular, reusable, and easier to understand. Let's break down the main concepts of OOP with simple examples.

1. Class

A class is like a blueprint for creating objects. It defines a set of properties (variables) and methods (functions) that the objects created from the class can use.

Examples:
 class Car {
  String color;
  String model;

  void drive() {
    print('The car is driving');
  }
}


In this example, Car is a class with two properties, color and model, and one method, drive.

2. Object

An object is an instance of a class. It is created from the blueprint defined by the class.

Example:
 void main() {
  Car myCar = Car();
  myCar.color = 'Red';
  myCar.model = 'Tesla Model S';
  myCar.drive(); // This will print 'The car is driving'
}

Here, myCar is an object of the Car class. We set its properties and call its method.


3. Constructor

A constructor is a special method that is called when an object is created. It initializes the object.

Example:
 class Car {
  String color;
  String model;

  Car(this.color, this.model);

  void drive() {
    print('The $color $model is driving');
  }
}

void main() {
  Car myCar = Car('Red', 'Tesla Model S');
  myCar.drive(); // This will print 'The Red Tesla Model S is driving'
}

In this example, the Car class has a constructor that takes color and model as parameters and initializes the object.


4. Inheritance

Inheritance allows a class to inherit properties and methods from another class. This helps in reusing code.

Example:
 class Vehicle {
  void honk() {
    print('Honking');
  }
}

class Car extends Vehicle {
  String color;
  String model;

  Car(this.color, this.model);

  void drive() {
    print('The $color $model is driving');
  }
}

void main() {
  Car myCar = Car('Red', 'Tesla Model S');
  myCar.drive(); // This will print 'The Red Tesla Model S is driving'
  myCar.honk();  // This will print 'Honking'
}

In this example, Car inherits from Vehicle, so myCar can use the honk method defined in Vehicle.


5. Polymorphism

Polymorphism means "many shapes". It allows one interface to be used for different data types.

Example:
 class Animal {
  void makeSound() {
    print('Some sound');
  }
}

class Dog extends Animal {
  @override
  void makeSound() {
    print('Bark');
  }
}

class Cat extends Animal {
  @override
  void makeSound() {
    print('Meow');
  }
}

void main() {
  Animal myDog = Dog();
  Animal myCat = Cat();

  myDog.makeSound(); // This will print 'Bark'
  myCat.makeSound(); // This will print 'Meow'
}

In this example, Dog and Cat classes override the makeSound method of the Animal class to provide their own implementation.


6. Encapsulation

Encapsulation is the concept of wrapping data and methods into a single unit (class) and restricting access to some of the object's components.

Example:
 class BankAccount {
  double _balance = 0.0;

  void deposit(double amount) {
    if (amount > 0) {
      _balance += amount;
    }
  }

  void withdraw(double amount) {
    if (amount > 0 && amount <= _balance) {
      _balance -= amount;
    }
  }

  double get balance => _balance;
}

void main() {
  BankAccount myAccount = BankAccount();
  myAccount.deposit(100);
  myAccount.withdraw(50);
  print(myAccount.balance); // This will print 50.0
}

In this example, _balance is private property (indicated by the underscore) and can only be modified through the deposit and withdraw methods, ensuring controlled access.


Summary

  • Class: Blueprint for creating objects.
  • Object: Instance of a class.
  • Constructor: Initializes an object.
  • Inheritance: Allows a class to inherit properties and methods from another class.
  • Polymorphism: Allows one interface to be used for different data types.
  • Encapsulation: Wraps data and methods into a single unit and restricts access to some components.

Dart Utilities

Dart utilities are tools or functions that help you perform common tasks more easily. For example, Dart provides utilities for working with dates and times, handling asynchronous operations, and managing data types.

Dart Utilities - Example using Dart's Math Library

The dart:math library provides utilities for mathematical operations.

import 'dart:math';

void main() {
  print('Square root of 16 is ${sqrt(16)}'); // Square root of 16 is 4.0
  print('Random number between 1 and 10: ${Random().nextInt(10) + 1}');
}


Dart – Date and Time

Date and time in Dart are used to work with dates and times. You can create, manipulate, and format dates and times using Dart's built-in classes and methods.

Dart – Date and Time

Dart's DateTime class is used to work with dates and times.

void main() {
  DateTime now = DateTime.now();
  print('Current date and time: $now');

  DateTime christmas = DateTime(2024, 12, 25);
  print('Christmas 2024 is on a ${christmas.weekday}');
}


Using await async in Dart

In Dart, await is used with async to handle asynchronous operations. When you mark a function as async, you can use await inside it to wait for asynchronous tasks to complete without blocking the program.

Using await async in Dart - Example with Future

await is used with async to wait for a Future to complete.

Future fetchData() async {
  print('Fetching data...');
  await Future.delayed(Duration(seconds: 2));
  print('Data fetched!');
}

void main() async {
  print('Start');
  await fetchData();
  print('End');
}


Data Enumeration in Dart

Data enumeration in Dart refers to the process of defining a fixed set of named values, often called enums. Enums make your code more readable and maintainable by giving meaningful names to values.

Data Enumeration in Dart - Example with Enums

Enums allow you to define a set of named constants.

enum Color { red, green, blue }

void main() {
  Color selectedColor = Color.blue;
  print('Selected color: $selectedColor');
}

Dart – Type System

Dart's type system is a way of categorizing different types of data in your program. Dart supports static typing, which means you can declare the type of a variable and the compiler checks that the variable is only assigned values of that type.

Dart–Type System - Example with Static Typing

Dart supports static typing, where you declare the type of a variable.

void main() {
  String name = 'Alice';
  int age = 30;
  double height = 5.6;
  bool isStudent = false;

  print('$name is $age years old, $height feet tall, and is a student: $isStudent');
}

Generators in Dart

Generators in Dart are used to create sequences of values lazily, meaning they are only computed when needed. This can be useful for generating large sequences of values without consuming a lot of memory.

Generators in Dart - Example with Iterable

Generators allow you to create sequences of values lazily.

Iterable generateNumbers(int n) sync* {
  for (int i = 1; i <= n; i++) {
    yield i;
  }
}

void main() {
  Iterable numbers = generateNumbers(5);
  print('Generated numbers: $numbers'); // Generated numbers: (1, 2, 3, 4, 5)
}

These examples showcase how Dart's utilities, date and time handling, asynchronous operations, data enumeration, type systems, and generators can be used in real-world scenarios.

In simple terms, Dart utilities help you do common tasks, date and time lets you work with dates, await async helps with asynchronous operations, data enumeration gives meaningful names to values, the type system categorizes data types, and generators create sequences of values lazily.

Dart Programs

Here are some simple Dart programs for beginners:

1. Calculate the Area of the Rectangle

void main() {
  double length = 5.0;
  double width = 3.0;
  double area = length * width;

  print('The area of the rectangle is $area');
} 

2. Check if a Number is Even or Odd

void main() {
  int number = 7;

  if (number % 2 == 0) {
    print('$number is even');
  } else {
    print('$number is odd');
  }
}
 

3. Print Multiplication Table

void main() {
  int num = 5;

  for (int i = 1; i <= 10; i++) {
    print('$num x $i = ${num * i}');
  }
} 

4. Calculate Factorial

void main() {
  int number = 5;
  int factorial = 1;

  for (int i = 1; i <= number; i++) {
    factorial *= i;
  }

  print('Factorial of $number is $factorial');
} 

5. Print Fibonacci Series

void main() {
  int n = 10;
  int first = 0, second = 1;

  print('Fibonacci Series:');
  for (int i = 1; i <= n; i++) {
    print('$first');
    int next = first + second;
    first = second;
    second = next;
  }
} 

These examples cover basic concepts like printing output, performing calculations, and using loops and conditionals, which are essential for beginners to understand Dart programming.

🔗 Learn Java in One Go