Flutter - Introduction to Dart Programming

Flutter - Introduction to Dart Programming

Flutter - Introduction to Dart Programming

Dart is an open-source general-purpose programming language. It is originally developed by Google. Dart is an object-oriented language with C-style syntax. It supports programming concepts like interfaces, classes. Unlike other programming languages, Dart doesn’t support arrays. Dart collections can be used to replicate data structures such as arrays, generics, and optional typing.

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: With Flutter, Dart enables hot reload, allowing developers to see code changes instantly without restarting the app. This significantly speeds up the development process..
  • Cross-Platform Support:With Dart and Flutter, you can write one codebase that works on multiple platforms (mobile, web, and desktop). This saves time and resources compared to developing separate apps for each platform.
  • High Performance: Dart compiles directly to native machine code, resulting in fast app startup times and better performance.
  • Object-Oriented: Dart's object-oriented approach makes it easy to manage complex applications using classes, inheritance, and interfaces.
  • Easy to Learn: Dart has a simple syntax, similar to other C-style languages, making it beginner-friendly.
  • Rich Standard Library: Dart comes with a comprehensive standard library, which includes packages for handling collections, file I/O, and networking, among other tasks. This makes development more efficient as you can rely on well-tested built-in functions..
  • Strong Typing with Flexibility: Dart is strongly typed, which means it catches errors early during development, helping prevent runtime errors and making your code more maintainable and less prone to bugs.
  • Asynchronous Programming: Dart has excellent support for asynchronous programming, with features like async, await, and Future.. This simplifies handling of concurrent operations like API requests and file processing, crucial for mobile apps and web services.
  • Optimized for UI Development:Dart is the language behind Flutter, making it highly optimized for building high-performance, beautiful, and responsive UIs across different platforms (iOS, Android, web, desktop).
  • Open-Source: Dart is open-source, with active contributions and strong community support, making it continuously evolve and improve.
  • Fast Compilation: Dart offers both Ahead-of-Time (AOT) compilation for fast startup times in production and Just-in-Time (JIT) compilation for rapid development and debugging, improving developer productivity..

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 a named storage location in memory used to store data that can be manipulated or retrieved during program execution. It acts as a container for values and can hold different types of data depending on its declaration.

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:

Dart list is similar to an array,which is ordered collection of object.A List in Dart is an ordered collection of items, where each item can be accessed by its index. A list can contain elements of the same type or different types, and it is one of the most commonly used data structures in Dart.

  1. Ordered:The items in a list have a specific order, and you can access each item using its position (index) in the list
  2. Indexed: Items in a list are indexed starting from 0, meaning the first item is at index 0, the second at index 1, and so on.
  3. Mutable: A list is dynamic and can be modified after it's created, meaning 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 an unordered collection of unique items. Unlike a list, a set cannot contain duplicate elements. Sets are particularly useful when you need to store a collection of items where duplicates are not allowed.

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 means checking a condition and deciding what code to run based on whether the condition is true or false. Dart provides if, if-else, and switch statements to make decisions in a program.

Loops are used to repeat a piece of code multiple times until a condition is no longer true. Dart supports different types of loops like for, for-in, while, and do-while.

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:

A function in Dart is a reusable block of code that performs a specific task. Functions help organize code, make it more readable, and reduce repetition by allowing you to reuse the same code.

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

Functions that do not take any input.

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

Functions that return a value 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

Functions without a name, often used for short tasks.

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

5. Arrow Functions

A shorthand for defining functions that consist of 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 programming paradigm based on the concept of objects, which are instances of classes. OOP allows you to structure software in a way that mirrors real-world entities and interactions.

Dart supports OOP with concepts like classes, objects, inheritance, polymorphism, encapsulation, and abstraction.


Key Concepts of OOP in Dart

1:Class

A class is a blueprint for creating objects. It defines properties and methods that objects of the class 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, promoting code reuse.


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 is the concept of restricting access to the internal state of an object and providing methods to interact with it. This is done using private fields and getter/setter methods.


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 allows methods to behave differently based on the object that calls them. In Dart, this is typically achieved through method overriding or interfaces.


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 concept of hiding the complex implementation details and providing a simplified interface. In Dart, this can be done using abstract classes or interfaces.


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
}
أحدث أقدم