Flutter - Introduction to Dart Programming

Flutter - Introduction to Dart Programming Flutter - Introduction to Dart Programming

Flutter - Introduction to Dart Programming

Dart is a modern, open-source programming language developed by Google, designed for building high-performance applications across mobile, web, and desktop. It’s best known as the backbone of Flutter, one of the most popular frameworks for cross-platform app development.Dart does not support arrays.

The following code shows a simple Dart program:


void main() {
print("Dart language is easy to learn"); }

Benefits of Dart Programming Language

Dart is a versatile and efficient programming language, especially popular for cross-platform development using Flutter. Here are some of its key benefits:

  • Fast Development: Thanks to Flutter, Dart supports hot reload, which allows you to instantly see changes in your app without restarting it. This saves time and boosts productivity during development..
  • Cross-Platform Support:With Dart and Flutter, you can write a single codebase that works on Android, iOS, web, and even desktop apps. No need to build separate apps for each platform — saving both time and effort. .
  • High Performance: Dart compiles directly into native machine code, which means your apps start quickly and run smoothly — with great performance and responsiveness.
  • Object-Oriented: Dart is object-oriented, just like Java or C++. It uses classes, inheritance, and interfaces to help you build clean and scalable applications — perfect for managing large codebases.
  • Easy to Learn:Dart’s syntax is straightforward and similar to other C-style languages (like JavaScript, C++, or Java). Beginners find it easy to pick up and start coding with minimal learning curve.
  • Rich Standard Library: Dart offers a comprehensive standard library, with built-in support for collections (like lists and maps), file input/output, and networking. You don’t always need third-party packages to get the job done.
  • Strong Typing with Flexibility:Dart is a strongly typed language, which means it catches errors at compile time — helping prevent bugs before they reach your users. At the same time, it gives you flexibility when needed, with optional typing.
  • Asynchronous Programming: Dart makes asynchronous programming easy using async, await, and Future. This is especially useful for tasks like API calls, file handling, or other operations that take time — without freezing the app.
  • Optimized for UI Development:Since Dart powers Flutter, it's tailor-made for building smooth, responsive, and visually appealing user interfaces on all platforms — whether it's mobile, web, or desktop.
  • Open-Source: Dart is completely open-source and backed by a strong developer community. It’s continuously evolving with new updates, contributions, and support — making it reliable for long-term projects.
  • Fast Compilation: Dart supports: AOT (Ahead-of-Time) compilation for fast startup and smooth performance in production apps. JIT (Just-in-Time) compilation for quick changes and debugging during development..

With these advantages, Dart has become a preferred choice for developers building modern, high-performance applications across multiple platforms.

Variables and Data Types in Dart

Definition of Variable

A variable is simply a name given to a spot in your computer's memory where data is stored. Think of it like a labeled box that holds a value — you can store something in it, change it later, or retrieve it whenever needed while your program is running. Depending on how it's defined, a variable can hold different types of data, such as numbers, text, or more complex information. It helps programmers manage and work with data in a clear, organized way.

Declaring Variables

  • Using

    Var

    :

    Automatically infers the type of the variable based on the assigned value.

    
    var name = 'Jackie'; // String type inferred
    var age = 25; // int type inferred
        
  • Using Explicit Types:

    Specify the type explicitly for clarity or to avoid unintended type inference.

    
    String name = 'Jackie';
    int age = 25;
    double height = 5.9;
        
  • Using

    final

    :

    For variables that are initialized once and never reassigned.

    
    final city = 'New York'; 
        
  • Using

    const

    :

    For compile-time constants.

    
    const pi = 3.14159; 
        

Special Notes

  • Null Safety:

    Dart has a null safety feature to prevent null errors.

    
    int? nullableNumber = null; // Allows null
    nullableNumber = 10;
    int nonNullNumber = nullableNumber!;
  • Default Values:

    Non-initialized variables default to

    null

  • Type Conversion:

    Convert between types as needed.

    
    int age = int.parse('25');
    String height = 5.9.toString(); 
        

Definition of Data Type

A data type defines the kind of data a variable can store, such as integers, floating-point numbers, text, or boolean values. It ensures that operations performed on the data are type-safe and valid.


Common Data Types in Dart
Data Type Description Example
int Integer numbers (whole numbers). int age = 25;
double Floating-point numbers (decimal numbers). double price = 19.99;
String Sequence of characters (text). String name = 'Flutter';
bool Boolean values

true

or

fale.

bool isLoggedIn = true;
List Ordered collection of items (arrays). List<int> numbers = [1, 2, 3];
Set Unordered collection of unique items. Set<String> colors = {'red', 'blue'};
Map Key-value pairs (dictionary-like). Map<String, int> ages = {'Jackie': 25};
dynamic Can hold any type of data (type changes). dynamic variable = 'Hello'; variable = 10;

Example


void main() {
final name = 'Jackie';
const gravity = 9.8;
int age = 25;
double height = 5.9;
bool isStudent = false;

print(name);
print(gravity);
print(age);
print(height);
print(isStudent);
}

Output

Output: Jackie

Output: 9.8

Output: 25

Output: 5.9

Output: false


List in Dart:

In Dart, a List is very similar to an array in other programming languages. It’s an ordered collection of items, meaning the elements are stored in a specific sequence, and each item can be accessed using its index. A List can hold values of the same type (like all integers or all strings), or even mixed types if needed. It’s one of the most frequently used data structures in Dart because of its flexibility and ease of use.

  1. Ordered:The elements in a list are stored in a specific order. This means that the position of each item matters and can be used to retrieve or modify data.
  2. Indexed: Items in a Dart list are indexed starting from 0. That means, the first item is at index 0, the second at index 1, and so on.
  3. Mutable: Dart lists are dynamic, which means you can add, remove, or change elements in the list.

  4. Types of list:

    1: Fixed-Length List:

    A list whose length is determined at creation and cannot be changed.

    
    List<int> numbers = List.filled(5, 0);
    
      

    2: Growable List:

    A list whose size can change at runtime (items can be added or removed).

    
    List<int> numbers = [1, 2, 3];
    
      

Key Operations on List:

  1. Accessing elements:Accessing elements: Using the index to retrieve or update an element in the list.

List<String> fruits = ['Apple', 'Banana', 'Cherry'];
print(fruits[0]);

  1. Adding elements: Using methods like add(), insert(), or addAll().

List<String> fruits = ['Apple', 'Banana', 'Cherry'];
fruits.add('Orange');

  1. Removing elements:Using methods like remove(), removeAt(), clear().

List<String> fruits = ['Apple', 'Banana', 'Cherry'];
fruits.remove('Banana');

  1. Iterating over a list:Using a loop to go through all elements.

void main() {
List<String> fruits = ['Apple', 'Banana', 'Cherry'];
for (var fruit in fruits) {
print(fruit);
}
}

Output:

Output: Apple

Output: Banana

Output: Cherry


Example: List of Integers:


void main() {
List<int> numbers = [1, 2, 3, 4, 5];
print(numbers); // Output: [1, 2, 3, 4, 5]
numbers.add(6);
print(numbers); // Output: [1, 2, 3, 4, 5, 6]
print(numbers[2]); // Output: 3
}

Example: List of Strings:


void main() {
List<String> fruits = ['Apple', 'Banana', 'Cherry'];
print(fruits); // Output: [Apple, Banana, Cherry]
fruits.add('Orange');
print(fruits); // Output: [Apple, Banana, Cherry, Orange]
}

dynamic Example:

The dynamic type in Dart allows a variable to hold any type of data and change its type during runtime.

Example: dynamic Variable:


void main() {
dynamic data = 'Hello, Flutter!';
print(data); // Output: Hello, Flutter!
data = 42;
print(data); // Output: 42
data = true;
print(data); // Output: true
}

Example: dynamic List:

You can also use dynamic for a list if you want the list to hold different types of data.


void main() {
List<dynamic> mixedList = [42, 'Hello', true, 3.14];
print(mixedList); // Output: [42, Hello, true, 3.14]
mixedList.add('New Element');
print(mixedList); // Output: [42, Hello, true, 3.14, New Element]
}

Definition of Map in Dart:

A Map in Dart is a collection of key-value pairs, where each key is unique, and it maps to a specific value. Maps are useful when you want to associate values with keys, like a dictionary in other programming languages.

Key Features:

  1. Keys must be unique, but values can be duplicated.
  2. You can access a value using its associated key.

Dart Code Example: Map


void main() {
Map<String, String> capitals = {
'USA': 'Washington, D.C.',
'Pakistan': 'Islamabad',
'Japan': 'New Delhi',
};
print(capitals['Pakistan']); // Output: Islamabad
}

Dart Code Example: Map Operations


void main() {
Map<String, int> ages = {
'Alice': 25,
'Bob': 30,
'Charlie': 28,
};

print(ages['Alice']);
ages['Diana'] = 32;
print(ages);
ages['Bob'] = 31;
print(ages);
print('\nIterating through Map:');
ages.forEach((key, value) {
print('$key is $value years old.');
});
}

Output

Output: 25

Output: {Alice: 25, Bob: 30, Charlie: 28, Diana: 32}

Output: {Alice: 25, Bob: 31, Charlie: 28, Diana: 32}

Iterating through Map:

Output: Alice is 25 years old.

Output: Bob is 31 years old.

Output: Charlie is 28 years old.

Output: Diana is 32 years old.


Definition of Set in Dart:

A Set in Dart is a collection of unique items where order doesn’t matter. Unlike a list, a set cannot contain duplicate values — each item appears only once, no matter how many times you try to add it. Sets are especially useful when you're working with data where repetition isn't allowed, such as storing a list of unique usernames, IDs, or any distinct elements.

  1. Unordered – The items in a set are not stored in any specific order.
  2. Unique Elements Only – No duplicates allowed. If you add a duplicate, Dart will ignore it.
  3. Efficient Lookups – Checking if an item exists in a set is generally faster than in a list.

Dart Set Example

void main() {
  Set<String> colors = {'Red', 'Blue', 'Green', 'Red'}; // Duplicate "Red" is ignored
  print(colors); // Output: {Red, Blue, Green}
}
  

Dart Set Example

void main() {
  // Creating a set of integers
  Set<int> numbers = {1, 2, 3, 4};

  // Adding elements
  numbers.add(5);
  print(numbers); // Output: {1, 2, 3, 4, 5}

  // Adding a duplicate element (it won't be added)
  numbers.add(3);
  print(numbers); // Output: {1, 2, 3, 4, 5}

  // Removing an element
  numbers.remove(2);
  print(numbers); // Output: {1, 3, 4, 5}

  // Checking if a set contains an element
  print(numbers.contains(4)); // Output: true
}
  

Decision Making and Loops:

Decision making in programming is all about making choices based on conditions. You check whether something is true or false, and then run different blocks of code depending on the result.

In Dart, you can use the following decision-making statements:

  • if — runs a block of code only if a condition is true.
  • if-else — runs one block if the condition is true, and another if it’s false.
  • switch — chooses one out of many possible blocks based on the value of a variable.
  • These tools help your program react differently depending on the situation.

Loops

Loops allow you to repeat a section of code multiple times, usually until a certain condition is no longer true. Instead of writing the same code again and again, you write it once and loop through it. Dart provides several types of loops:

  • for loop — best when you know exactly how many times to repeat.
  • for-in loop — ideal for going through each item in a collection, like a list or set.
  • while loop — keeps running as long as a condition is true.
  • do-while loop — runs the code at least once, then checks the condition.

void main() {
for (var i = 1; i <= 10; i++) {
if (i % 2 == 0) { print(i); } } }

The above code prints the even numbers from 1 to 10.


Functions in Dart:

In Dart, a function is a reusable block of code that performs a specific task. Instead of writing the same code again and again, you can put that logic inside a function and call it whenever needed.Functions help to: Organize code better ,Make it easier to read, Avoid repetition

Syntax of a Function

ReturnType functionName(ParameterType parameter) { 
return value;
}

Example:Function

void main() {
greet(); // Calling the function
}
void greet() {
print('Hello, Dart!'); // Output: Hello, Dart!
}

Types of Functions

1. Functions with No Parameters

These functions don’t take any input. They simply run a block of code when called.

void main() {
showMessage();
}
void showMessage() {
print('Welcome to Dart!');
}

2. Functions with Parameters

Functions that take input values.

void main() {
greetUser('Alice');
}
void greetUser(String name) {
print('Hello, $name!'); // Output: Hello, Alice!
}

3. Functions with Return Value

These functions accept input values (called parameters) that you can use inside the function. Functions with Return Value Some functions perform a task and then return a result back to the caller.

void main() {
int result = add(10, 20);
print('Sum: $result'); // Output: Sum: 30
}
int add(int a, int b) {
return a + b;
}

4. Anonymous Functions

An anonymous function is a function without a name. These are useful when you need a short function temporarily — often used with lists, buttons, or callbacks.

void main() { 
var numbers = [1, 2, 3]; numbers.forEach((number) { print(number * 2); // Output: 2, 4, 6 }); }

5. Arrow Functions

Arrow functions are a shorter way to write functions that return a single expression.

void main() {
print(add(3, 4)); // Output: 7
}
int add(int a, int b) => a + b;

void main() {
add(7, 5);
}
void add(int a, int b) {
int c;
c = a + b;
print(c); // Output: 12
}

Object Oriented Programming

Object-Oriented Programming (OOP) is a style of programming that organizes code around objects, which are based on classes. This approach helps structure software in a way that reflects real-world things and how they interact. Dart fully supports OOP and provides powerful features like classes, objects, inheritance, encapsulation, polymorphism, and abstraction — all of which help in writing clean, modular, and reusable code.


Key Concepts of OOP in Dart

1:Class

A class is like a blueprint or template for creating objects. It defines what properties (data) and methods (functions) the objects created from it will have.


   
class Person {
String name;
int age;
Person(this.name, this.age);
void introduce() {
print('Hello, my name is $name and I am $age years old.');
}
}

2:Object

An object is an instance of a class. You create an object by using the new keyword or directly calling the class.


void main() {
var person1 = Person('Alice', 30);
person1.introduce(); // Output: Hello, my name is Alice and I am 30 years old.
}

3:Inheritance

Inheritance allows a class to inherit properties and methods from another class. This promotes code reuse and helps avoid repetition.


class Animal {
void speak() {
print('Animal makes a sound');
}
}
class Dog extends Animal {
void speak() {
print('Dog barks');
}
}
void main() {
var dog = Dog();
dog.speak(); // Output: Dog barks
}

4:Encapsulation

Encapsulation means hiding the internal details of a class and allowing access only through specific methods. In Dart, you can make fields private by adding an underscore (_), and then use getters and setters.


class BankAccount {
double _balance = 0.0;
double get balance => _balance;
void deposit(double amount) {
if (amount > 0) {
_balance += amount;
}
}
}
void main() {
var account = BankAccount();
account.deposit(100);
print(account.balance); // Output: 100.0
}

5:Polymorphism

Polymorphism means having many forms. It allows different classes to define methods with the same name but different behaviors.


class Animal {
void speak() {
print('Animal makes a sound');
}
}
class Dog extends Animal {
@override
void speak() {
print('Dog barks');
}
}
class Cat extends Animal {
@override
void speak() {
print('Cat meows');
}
}
void main() {
var animal = Animal();
var dog = Dog();
var cat = Cat();
animal.speak(); // Output: Animal makes a sound
dog.speak(); // Output: Dog barks
cat.speak(); // Output: Cat meows
}

6:Abstraction

Abstraction is the idea of hiding unnecessary details and showing only the essential features. In Dart, you can use abstract classes or interfaces to achieve abstraction.


abstract class Shape {
void draw();
}
class Circle extends Shape {
@override
void draw() {
print('Drawing a circle');
}
}
void main() {
var circle = Circle();
circle.draw(); // Output: Drawing a circle
}

Class with Getter and Setter Example in Dart


class Student {
String studentName;
// Getter method
String get name {
return studentName;
}
// Setter method
void set name(String name) {
this.studentName = name;
}
// Function definition
void showName() {
print(studentName);
}
}
void main() {
// Object creation
Student student = new Student();
student.studentName = "John Doe";
student.showName(); // Function call
}
أحدث أقدم