0% found this document useful (0 votes)
3 views44 pages

Mobile Unit1

The document outlines the fundamentals of the Dart programming language, including its development environment, key concepts, and object-oriented programming principles. It covers installation, data types, control flow structures, functions, and the four pillars of OOP: encapsulation, inheritance, polymorphism, and abstraction. Additionally, it discusses Dart libraries, managing dependencies, and practical examples of encapsulation and abstraction in Dart code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views44 pages

Mobile Unit1

The document outlines the fundamentals of the Dart programming language, including its development environment, key concepts, and object-oriented programming principles. It covers installation, data types, control flow structures, functions, and the four pillars of OOP: encapsulation, inheritance, polymorphism, and abstraction. Additionally, it discusses Dart libraries, managing dependencies, and practical examples of encapsulation and abstraction in Dart code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Learning Outcome 1: Apply Basics of Dart

1.1 Development environment is correctly prepared according to the


operating system.
1.2 Dart concepts are appropriately applied according to the dart standards.
1.3 Object-oriented principles are properly implemented in accordance with
the dart syntax.
1.4 Dart Libraries and packages are appropriately used based the
application requirements
2.1 Flutter environment is properly prepared based on system
requirements.
1. Development Environment Preparation
1.1 Introduction to Dart
●​ Dart is an open-source, client-optimized programming language developed by
Google.​
●​ Primary use: building mobile, web, desktop, and backend applications.​
●​ Dart is the core language behind Flutter, Google’s UI framework.​

Features & Characteristics


●​ Strongly typed, modern, and object-oriented.​
●​ Just-In-Time (JIT) compilation (fast development & debugging).​
●​ Ahead-Of-Time (AOT) compilation (optimized production code).​
●​ Supports both synchronous and asynchronous programming.​
●​ Easy to learn for developers familiar with Java, C#, or JavaScript.​

Dart Frameworks / Use cases


●​ Flutter (cross-platform UI toolkit).​
●​ AngularDart (web apps).​
●​ Backend development (with frameworks like Aqueduct, Dart Frog).​
●​ CLI tools & scripting.​

1.2 Installation of Key Tools


For Windows & macOS:
●​ Install Dart SDK (via dart.dev).​
●​ Install Visual Studio Code (VS Code) or Android Studio.​
●​ Add Dart & Flutter plugins in IDE.​
Verify installation:​

dart --version
flutter doctor

Testing Dart environment:


Create a simple Dart file:​

void main() {
print("Hello Dart!");
}

Run it with:​

dart run filename.dart

2. Applying Dart Concepts


2.1 Key Terms
●​ Data types: int, double, String, bool, List, Map, dynamic.​
●​ Variables: Declared with var, final, const, or explicit type.​
●​ Native Apps: Apps built specifically for a single platform (e.g., Android, iOS).​
●​ Cross-Platform Apps: Apps that run on multiple platforms with a single
codebase (e.g., using Flutter).​

2.2 Variables and Data Types


int age = 20;
double price = 19.99;
String name = "Ronald";
bool isStudent = true;
var country = "Rwanda"; // type inferred
final pi = 3.14; // value set once
const gravity = 9.8; // compile-time constant
2.3 Control Flow Structures
●​ Conditional statements:​

if (age > 18) {


print("Adult");
} else {
print("Minor");
}

●​ Switch statements:​

switch (day) {
case "Monday": print("Start of week"); break;
case "Friday": print("Weekend soon!"); break;
default: print("Midweek");
}

●​ Iterating statements:​

for (int i = 0; i < 5; i++) {


print("Count: $i");
}
while (x < 5) {
print(x);
x++;
}
do {
print("Runs at least once");
} while (x < 10);

2.4 Functions
●​ Declaring functions​
void greet(String name) {
print("Hello, $name!");
}

●​ Return types​

int add(int a, int b) {


return a + b;
}

●​ Built-in functions: e.g., print(), toString(), length.​


●​ Arrow functions​

int multiply(int a, int b) => a * b;

3. Object-Oriented Programming in Dart


3.1 Classes and Objects
class Car {
String brand;
int year;
Car(this.brand, this.year);
void display() {
print("Car: $brand, Year: $year");
}
}
void main() {
Car myCar = Car("Toyota", 2021);
myCar.display();
}

3.2 Inheritance
class Animal {
void sound() => print("Animal makes a sound");
}
class Dog extends Animal {
@override
void sound() => print("Bark");
}

3.3 Polymorphism
●​ Objects of subclasses can be treated as objects of the parent class.​

Animal pet = Dog();


pet.sound(); // Outputs: Bark

3.4 Encapsulation
class BankAccount {
double _balance = 0; // private variable
void deposit(double amount) => _balance += amount;
double get balance => _balance;
}

3.5 Abstraction
●​ Done using abstract classes or interfaces.​

abstract class Shape {


void draw();
}
class Circle extends Shape {
@override
void draw() => print("Drawing Circle");
}

4. Dart Libraries and Packages


4.1 Importing and Using Libraries
import 'dart:math';
void main() {
print(sqrt(25)); // 5.0
}

4.2 Built-in Dart Libraries


●​ dart:core – built-in types (int, String, List, Map).​
●​ dart:math – math utilities.​
●​ dart:async – asynchronous programming.​
●​ dart:io – file, socket, and HTTP I/O.​

4.3 Managing Dependencies with Pub


●​ pubspec.yaml controls packages.​

dependencies:
http: ^1.1.0

●​ Run:​

dart pub get

4.4 Using External Packages


Example: http package for API requests.
import 'package:http/http.dart' as http;
void main() async {
var response = await
http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));
print(response.body);
}
Fast forward to deep understanding OOP

Understanding the Four Pillars of OOP

1. Encapsulation
Encapsulation is the bundling of data and methods that operate on the data within a
single unit, known as a class. It hides the internal state of an object from the outside
world, only exposing the necessary functionalities through well-defined interfaces.

In Dart, encapsulation is achieved through access modifiers such as public, private,


and protected. By default, members are public, but you can also mark them as private
using an underscore (_).

Example:

class BankAccount {

double _balance = 0; // Private property

void deposit(double amount) {


_balance += amount;

void withdraw(double amount) {

if (_balance >= amount) {

_balance -= amount;

} else {

print('Insufficient funds.');

}
double getBalance() {

return _balance;

void main() {

var account = BankAccount();

account.deposit(1000);

print('Current balance: ${account.getBalance()}'); // Output: Current balance: 1000

account.withdraw(500);

print('Remaining balance: ${account.getBalance()}'); // Output: Remaining balance:


500
}

2. Inheritance
Inheritance is a mechanism that allows a class (subclass) to inherit properties and
methods from another class (superclass). This promotes code reuse and establishes a
hierarchical relationship between classes.

Example:

class Animal {

void speak() {

print('Animal speaks.');

class Dog extends Animal {


@override

void speak() {

print('Dog barks.');

void main() {

var dog = Dog();

dog.speak(); // Output: Dog barks.

3. Polymorphism
Polymorphism allows objects of different classes to be treated as objects of a common
superclass. This enables flexibility and extensibility in code.
Example:

class Shape {

void draw() {

print('Drawing a shape.');

class Circle extends Shape {

@override

void draw() {

print('Drawing a circle.');
}

class Rectangle extends Shape {

@override

void draw() {

print('Drawing a rectangle.');

void main() {
Shape circle = Circle();

Shape rectangle = Rectangle();

circle.draw(); // Output: Drawing a circle.

rectangle.draw(); // Output: Drawing a rectangle.

4. Abstraction
Abstraction is the process of hiding complex implementation details and showing only
the essential features of an object. It helps in reducing programming complexity and
managing large codebases effectively.

Example:

abstract class Animal {

void speak();
}

class Dog extends Animal {

@override

void speak() {

print('Dog barks.');

void main() {

var dog = Dog();


dog.speak(); // Output: Dog barks.

Method Overriding and Overloading

Method Overriding
Method overriding occurs when a subclass provides a specific implementation of a
method that is already defined in its superclass. It allows subclasses to tailor the
behavior of inherited methods to suit their specific needs.

Example:

class Animal {

void speak() {

print('Animal speaks.');

}
class Dog extends Animal {

@override

void speak() {

print('Dog barks.');

void main() {

var dog = Dog();

dog.speak(); // Output: Dog barks.


}

Method Overloading
Method overloading refers to the ability to define multiple methods with the same
name but with different parameters. Dart does not support method overloading
directly, but you can achieve similar functionality using optional parameters or named
parameters.

Example:

class Calculator {

int add(int a, int b) {

return a + b;

double add(double a, double b) {

return a + b;
}

void main() {

var calc = Calculator();

print(calc.add(2, 3)); // Output: 5

print(calc.add(2.5, 3.5)); // Output: 6.0

Understanding Inheritance
Inheritance is a mechanism in which a new class (subclass) is created from an existing
class (superclass), inheriting its properties and methods. This promotes code reuse
and establishes a hierarchical relationship between classes.

Types of Inheritance
1. Single Inheritance
Single inheritance occurs when a class inherits properties and methods from a single
superclass. In Dart, a class can extend only one superclass.

Example:

class Animal {

void eat() {

print('Animal is eating.');

class Dog extends Animal {

void bark() {
print('Dog is barking.');

void main() {

var dog = Dog();

dog.eat(); // Output: Animal is eating.

dog.bark(); // Output: Dog is barking.

In this example, the Dog class inherits the eat() method from the Animal class.

2. Multilevel Inheritance
Multilevel inheritance involves a chain of inheritance where a subclass becomes a
superclass for another class. It establishes a hierarchical relationship with multiple
levels of inheritance.

Example:

class Animal {

void eat() {

print('Animal is eating.');

class Dog extends Animal {

void bark() {
print('Dog is barking.');

class Labrador extends Dog {

void swim() {

print('Labrador is swimming.');

void main() {
var labrador = Labrador();

labrador.eat(); // Output: Animal is eating.

labrador.bark(); // Output: Dog is barking.

labrador.swim(); // Output: Labrador is swimming.

Here, the Labrador class inherits from the Dog class, which in turn inherits from the
Animal class.

3. Hierarchical Inheritance
Hierarchical inheritance involves multiple subclasses inheriting from a single
superclass. Each subclass shares common characteristics from the superclass but
may have its own specialized behavior.

Example:

class Animal {

void eat() {
print('Animal is eating.');

class Dog extends Animal {

void bark() {

print('Dog is barking.');

class Cat extends Animal {


void meow() {

print('Cat is meowing.');

void main() {

var dog = Dog();

dog.eat(); // Output: Animal is eating.

dog.bark(); // Output: Dog is barking.

var cat = Cat();


cat.eat(); // Output: Animal is eating.

cat.meow(); // Output: Cat is meowing.

In this example, both Dog and Cat classes inherit from the Animal class, sharing its
eat() method.

Understanding Encapsulation
Encapsulation is a core principle of Object-Oriented Programming (OOP), aimed at
bundling the data (variables) and methods (functions) that operate on the data into a
single unit, known as a class. This approach restricts direct access to some of the
object’s components, which is essential for preventing unintended interference and
misuse. In Dart and Flutter, encapsulation is achieved in three primary ways: member
variable encapsulation, function encapsulation, and class encapsulation. Let’s explore
each type in detail with practical examples.

1. Member Variable Encapsulation


Member variable encapsulation involves protecting the internal state of an object by
making its variables private and providing controlled access through public methods.
This ensures that the object’s data can only be modified in a defined manner.
Example:

class Person {

String _name; // Private variable

Person(this._name);

// Getter for _name

String get name => _name;

// Setter for _name

set name(String name) {


if (name.isNotEmpty) {

_name = name;

void main() {

var person = Person('John');

print(person.name); // Output: John

person.name = 'Doe';

print(person.name); // Output: Doe


}

In this example, the _name variable is private and can only be accessed or modified
through the getter and setter methods. This encapsulation ensures that any
modification to _name is validated.

2. Function Encapsulation
Function encapsulation involves making some methods private to control how the
object’s data is manipulated internally. Only the necessary methods are exposed
publicly, keeping the internal implementation hidden.

Example:

class Calculator {

// Public method

int add(int a, int b) {

return _performAddition(a, b);

}
// Private helper method

int _performAddition(int a, int b) {

return a + b;

void main() {

var calc = Calculator();

print(calc.add(2, 3)); // Output: 5

}
Here, the _performAddition method is private and is only accessible within the
Calculator class. The public add method exposes the functionality while keeping the
internal workings hidden.

3. Class Encapsulation
Class encapsulation involves bundling related variables and methods into a single
class. This promotes modularity and reusability, making the code more organized and
easier to manage.

Example:

class Car {

String _model;

int _year;

Car(this._model, this._year);
// Public method to display car info

void displayInfo() {

print('Model: $_model, Year: $_year');

void main() {

var myCar = Car('Tesla', 2021);

myCar.displayInfo(); // Output: Model: Tesla, Year: 2021

In this example, the Car class encapsulates the _model and _year variables along with
the displayInfo method. This organization ensures that all information and behavior
related to a car are grouped together.
Understanding Abstraction
Abstraction is a key principle in Object-Oriented Programming (OOP) that simplifies
complex systems by modeling classes appropriate to the problem. It helps in hiding
the implementation details and showing only the functionality to the user. In Dart and
Flutter, abstraction can be applied in various forms to create clean, maintainable, and
modular code. This blog will cover different types of abstraction in OOP: data
abstraction, process abstraction, abstraction using public specifiers, and abstraction
using private classifiers. Let’s dive in!

1. Data Abstraction
Data abstraction focuses on exposing only essential features and hiding unnecessary
details. In Dart, data abstraction is commonly achieved using abstract classes and
interfaces.

Example:

abstract class Animal {

void sound(); // Abstract method

}
class Dog extends Animal {

@override

void sound() {

print('Bark');

void main() {

Animal myDog = Dog();

myDog.sound(); // Output: Bark


}

In this example, the Animal class defines an abstract method sound(), which is
implemented by the Dog class. The implementation details of sound() are hidden from
the user of the Animal class, exposing only the necessary functionality.

2. Process Abstraction
Process abstraction involves abstracting complex processes or operations into simpler,
more manageable methods. This helps in breaking down complex functionalities into
smaller, reusable methods.

Example:

class MathOperations {

double calculateArea(double radius) {

return _calculateCircleArea(radius);

}
// Private method for detailed calculation

double _calculateCircleArea(double radius) {

return 3.14 * radius * radius;

void main() {

var math = MathOperations();

print(math.calculateArea(5)); // Output: 78.5

Here, the MathOperations class abstracts the process of calculating the area of a circle
into the _calculateCircleArea private method. The user interacts with the calculateArea
method without needing to know the underlying calculations.
3. Abstraction Using Public Specifiers
Public specifiers in Dart are used to expose certain parts of a class while keeping
others hidden. This is essential for defining a clear interface for the class while
protecting its internal state.

Example:

class BankAccount {

String _accountNumber;

double _balance;

BankAccount(this._accountNumber, this._balance);

// Public method to get account balance

double get balance => _balance;


// Public method to deposit money

void deposit(double amount) {

if (amount > 0) {

_balance += amount;

void main() {

var account = BankAccount('123456789', 1000.0);


account.deposit(500);

print(account.balance); // Output: 1500.0

In this example, the _accountNumber and _balance variables are private, but the
balance getter and deposit method are public. This allows controlled access to the
balance while keeping the account number hidden.

4. Abstraction Using Private Classifiers


Private classifiers in Dart are used to encapsulate details within a class, making
certain properties and methods inaccessible from outside the class.

Example:

class Employee {

String _name;

double _salary;
Employee(this._name, this._salary);

// Public method to get employee details

String getDetails() {

return 'Name: $_name, Salary: $_salary';

// Private method to calculate bonus

double _calculateBonus() {

return _salary * 0.1;


}

// Public method to get bonus

double get bonus => _calculateBonus();

void main() {

var employee = Employee('Alice', 50000);

print(employee.getDetails()); // Output: Name: Alice, Salary: 50000

print(employee.bonus); // Output: 5000.0

}
In this example, the _calculateBonus method is private and can only be accessed
within the Employee class. The bonus getter exposes the calculated bonus, hiding the
actual calculation process

You might also like