Mobile App Development Unit-2 Notes
Mobile App Development Unit-2 Notes
Tilavalli
BLDEA Commerce, BHS Arts & TGP Science College, Jamkhandi
MOBILE APPLICATION
DEVELOPMENT
UNIT-2 NOTES
Using `var`
The `var` keyword is used when you want the compiler to infer the type of the variable based on
the assigned value.
void main() {
var name = 'John Doe'; // Type inferred as String
var age = 30; // Type inferred as int
var height = 5.9; // Type inferred as double
print(name);
print(age);
print(height);
}
Explicit Typing
You can explicitly declare the type of the variable.
void main() {
String name = 'John Doe';
int age = 30;
double height = 5.9;
print(name);
print(age);
print(height);
}
A `final` variable can be set only once and is initialized when accessed.
void main() {
final name = 'John Doe';
final int age = 30;
print(name);
print(age);
}
void main() {
const name = 'John Doe';
const int age = 30;
print(name);
print(age);
}
Data Types
Dart supports various data types including numeric values, strings, and boolean types.
Numeric Values
Dart has two numeric types: `int` and `double`.
void main() {
int age = 30;
int year = 2023;
print(age);
print(year);
}
double: Represents floating-point values.
void main() {
double height = 5.9;
double weight = 70.5;
print(height);
print(weight);
}
Strings
Strings are a sequence of characters enclosed in single or double quotes.
void main() {
String singleQuotes = 'Hello, Dart!';
String doubleQuotes = "Hello, Dart!";
print(singleQuotes);
print(doubleQuotes);
}
void main() {
String name = 'John';
int age = 30;
String greeting = 'Hello, my name is $name and I am $age years
old.';
print(greeting);
}
Boolean Types
The `bool` type represents Boolean values, either `true` or `false`.
void main() {
bool isVisible = true;
bool isEnabled = false;
print(isVisible);
print(isEnabled);
}
Chapter-2
Operators in Dart
In Dart programming, operators are specialized symbols that perform operations on
values (operands). They provide a concise and readable way to manipulate data and
control program flow, forming the backbone of any Dart program.
Arithmetic Operators
Sl.No Symbol Operator Name Syntax Example Explanation
Relational Operators
Logical Operators
Sl.No Symbol Operator Name Syntax Example Explanation
Assignment Operators
Assigns a value to a
1 = Assignment a = b int a = 5
variable
Conditional Operators
Sl.No Symbol Operator Name Syntax Example Explanation
condition
Returns one of two values
1 ?: Conditional ? expr1 : (5 > 3) ? 5 : 3
based on a condition
expr2
String? Name;
String greeting = name ?? "There";
// greeting will be "There" if name is null
Chapter-3
Flow Control Constructs
Flow control constructs are fundamental elements in programming languages that
manage the order in which statements, instructions, or function calls are executed or
evaluated. They enable the programmer to dictate the sequence and conditions under
which different parts of the code are executed, making the program dynamic and
responsive to various inputs and conditions.
1. `if` Statement
The `if` statement allows you to execute a block of code if a specified condition is true.
Syntax
if (condition) {
// code to execute if the condition is true
}
Example: Checking if a user is an adult.
void main() {
int age = 20;
if (age >= 18) {
print('You are an adult.');
}
}
Explanation:
2. `if-else` Statement
The `if-else` statement allows you to execute one block of code if the condition is true and
another block if the condition is false.
Syntax:
if (condition) {
// code to execute if the condition is true
} else {
// code to execute if the condition is false
}
Example: Checking if a user is logged in or not.
void main() {
bool isLoggedIn = true;
if (isLoggedIn) {
print('Welcome back!');
} else {
print('Please log in.');
}
}
Explanation:
Syntax:
if (condition1) {
// code to execute if condition1 is true
} else if (condition2) {
// code to execute if condition2 is true
} else {
// code to execute if none of the conditions are true
}
Example: Determining the level of discount based on the purchase
amount.
void main() {
double purchaseAmount = 150.0;
if (purchaseAmount > 200) {
print('You get a 20% discount.');
} else if (purchaseAmount > 100) {
print('You get a 10% discount.');
} else if (purchaseAmount > 50) {
print('You get a 5% discount.');
} else {
print('No discount available.');
}
}
Explanation:
4. `switch` Statement
The `switch` statement provides a way to dispatch execution to different parts of code based on
the value of an expression. It's often used as an alternative to a series of `if-else` statements.
Syntax:
switch (expression) {
case value1:
// code to execute if expression == value1
break;
case value2:
// code to execute if expression == value2
break;
// more cases
default:
// code to execute if none of the cases match
}
1. `for` Loop
The `for` loop is used when the number of iterations is known before entering the loop.
It consists of three parts: initialization, condition, and increment/decrement.
Syntax:
for (initialization; condition; increment/decrement) {
// code to be executed
}
Explanation:
2. `while` Loop
The `while` loop is used when the number of iterations is not known beforehand. It continues to
execute as long as the condition is true.
Syntax:
while (condition) {
// code to be executed
}
Explanation:
3. `do-while` Loop
The `do-while` loop is similar to the `while` loop, but it ensures that the code block runs at least
once because the condition is checked after the block has executed.
Syntax:
do {
// code to be executed
} while (condition);
do {
print(i);
i++;
} while (i <= 5);
}
Explanation:
Break Statement
The `break` statement terminates the loop immediately, exiting it before the condition is false.
Syntax:
for (initialization; condition; increment/decrement) {
if (condition) {
break;
}
// code to be executed
}
Example: Exiting a loop when a number is found.
void main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
print('Found 5, exiting loop.');
break;
}
print(i);
}
}
Explanation:
1. The loop initializes `i` to 1 and increments it up to 10.
2. If `i` equals 5, it prints a message and breaks out of the loop.
3. The loop terminates when 5 is found, only printing numbers 1 to 4.
Continue Statement
The `continue` statement skips the current iteration and moves to the next iteration of the loop.
Syntax:
for (initialization; condition; increment/decrement) {
if (condition) {
continue;
}
// code to be executed
}
Explanation:
1. The loop initializes `i` to 1 and increments it up to 10.
2. If `i` is an even number (`i % 2 == 0`), it skips the current iteration using `continue`.
3. It only prints odd numbers (1, 3, 5, 7, 9).
Chapter-5
Functions in Dart
Functions are self-contained blocks of code designed to perform a specific task. They allow for
better organization, modularity, and reusability of code. By breaking down complex tasks into
smaller, manageable pieces, functions make code easier to read, maintain, and debug.
Benefits of Functions:
● Code Reusability: Functions allow you to write code once and reuse it multiple times.
● Modularity: Functions break down complex problems into smaller, manageable sub-
problems.
● Maintainability: Functions make code easier to read, understand, and maintain.
● Abstraction: Functions hide the implementation details and expose only the necessary
interface.
To use a function, you call it by its name and pass the required arguments.
Syntax:
functionName(argument1, argument2);
Example:
void main() {
int result = add(5, 3);
print(result); // Output: 8
}
Explanation:
1. The `add` function is called with arguments `5` and `3`.
2. The result (8) is stored in the variable `result` and printed to the console.
Positional Parameters are parameters that are mandatory and must be provided in the correct
order when the function is called.
Syntax:
ReturnType functionName(ParameterType parameter1, ParameterType
parameter2) {
// function body
return value;
}
void main() {
print(calculateArea(5, 3)); // Output: 15
}
Explanation:
1. The `calculateArea` function takes two integer parameters, `length` and `width`.
2. It returns the product of `length` and `width` as the area.
Optional Positional Parameters: are parameters that are optional and can be omitted when
calling the function. If omitted, they take on a default value if provided.
Syntax:
ReturnType functionName(ParameterType parameter1, [ParameterType
parameter2 = defaultValue]) {
// function body
return value;
}
void main() {
print(greet("John")); // Output: Hello, Mr. John
print(greet("John", "Dr.")); // Output: Hello, Dr. John
}
Explanation:
1. The function `greet` takes a mandatory parameter `name` and an optional parameter `title`.
2. If `title` is not provided, it defaults to "Mr."
void main() {
print(greet("John")); // Output: Hello, Mr. John
print(greet("John", "Dr.")); // Output: Hello, Dr. John
}
Explanation:
1. The `title` parameter can be null.
2. If `title` is null, it defaults to "Mr." using the null-aware operator (`??=`).
6. Named Parameters
Named Parameters: are parameters that are identified by name rather than position. They
make function calls more readable and allow for specifying only the necessary parameters.
Syntax:
void main() {
print(greet(name: "John")); // Output: Hello, Mr. John
print(greet(name: "John", title: "Dr.")); // Output: Hello, Dr. John
}
void main() {
print(greet(name: "John", title: "Mr.")); // Output: Hello, Mr. John
print(greet(name: "John", title: "Dr.")); // Output: Hello, Dr. John
}
Explanation:
1. The function `greet` takes named parameters `name` and `title`.
2. `name` is required, while `title` is optional with a default value of "Mr."
Null Safety with Named Parameters:
void main() {
print(greet(name: "John")); // Output: Hello, Mr. John
print(greet(name: "John", title: "Dr.")); // Output: Hello, Dr. John
}
Explanation:
1. The `title` parameter can be null.
2. If `title` is null, it defaults to "Mr." using the null-aware operator (`??=`).
7. Arrow Functions
Arrow Functions provide a concise syntax for functions with a single expression.
Syntax
ReturnType functionName(ParameterType parameter) => expression;
Example:
int square(int x) => x * x;
void main() {
print(square(4)); // Output: 16
}
Explanation:
1. The function `square` takes an integer `x` and returns its square.
2. The arrow (`=>`) replaces the need for curly braces and the `return` keyword for single-
expression functions.
Chapter-6
Collections in Dart
1. Define Collections
Collections in Dart are data structures that store multiple values. They are used to hold a group
of objects and provide various methods to manage these objects efficiently.
2. Collection Types:
The main collection types in Dart are:
● List
● Map
Lists in Dart
1. Define List:
A List in Dart is an ordered collection of items, where each item can be accessed by its index.
Lists are similar to arrays in other programming languages.
Example Explanation:
Accesses the first element of the list `fruits`.
fruits.add('Orange');
Example Explanation:
Adds 'Orange' to the end of the list `fruits`.
Example Explanation:
Changes the first element of the list to 'Strawberry'.
Example Explanation:
Removes 'Banana' from the list `fruits`.
Example Explanation
Filters the list to include only fruits that start with 'S' and converts the result back to a list.
10. Converting Maps to List of Objects Using `map()` and `toList()` Method:
Maps in Dart
1. Define Map:
A Map in Dart is an unordered collection of key-value pairs, where each key is unique and is
used to access its corresponding value.
2. Creation of Map:
Example Explanation:
This creates a map with keys 'Alice' and 'Bob', and their corresponding values 50 and 75.
Example Explanation:
This creates an empty map and then adds key-value pairs for 'USA' and 'Canada'.
Example Explanation:
Creates a map where the keys are integers and the values are strings.
Example Explanation:
Accesses the value associated with the key 'Alice'.
Example Explanation:
Iterates over each entry in the map and prints the key and value.
Example Explanation:
Checks if the key 'Bob' exists in the map.
scores['Alice'] = 85;
Example Explanation:
Updates the value associated with the key 'Alice' to 85.
Example Explanation:
Removes the key-value pair with the key 'Bob' from the map.
Chapter-7
Object-Oriented Programming (OOP) in Dart
1. Defining Classes
A class is a blueprint for creating objects. It defines properties (instance variables) and methods
(functions).
class Person {
String name;
int age;
void greet() {
print('Hello, my name is $name.');
}
}
Example Explanation:
This defines a `Person` class with two instance variables (`name` and `age`) and a method
(`greet`).
class Calculator {
int add(int a, int b) {
return a + b;
}
}
Example Explanation:
The `Calculator` class has an `add` method that takes two integers and returns their sum.
Example Explanation:
The `greet` method has two required named parameters (`name` and `age`). You must provide
values for these parameters when calling the method.
4. Creating Objects
You create an object by calling the class constructor.
Person person = Person();
person.name = 'Alice';
person.age = 30;
person.greet(); // Output: Hello, my name is Alice.
Example Explanation:
Creates a `Person` object and assigns values to its properties.
5. Constructors
Constructors are special methods to initialize objects. Dart supports named constructors and
default constructors.
class Person {
String name;
int age;
Person(this.name, this.age);
Person.named(this.name, {this.age = 0});
}
Example Explanation:
The `Person` class has a default constructor and a named constructor (`named`) with an
optional parameter `age`.
6. Subclasses
A subclass is a class that extends another class (superclass).
class Parent {
void show() {
print('Parent class');
}
}
class Child extends Parent {
void display() {
print('Child class');
}
}
Example Explanation:
The `Child` class extends the `Parent` class, inheriting the `show` method and adding its own
`display` method.
7. Polymorphism
Polymorphism allows methods to do different things based on the object it is acting upon.
class Animal {
void sound() {
print('Some sound');
}
}
class Dog extends Animal {
@override
void sound() {
print('Bark');
}
}
class Cat extends Animal {
@override
void sound() {
print('Meow');
}
}
void main() {
Animal myDog = Dog();
Animal myCat = Cat();
myDog.sound(); // Output: Bark
myCat.sound(); // Output: Meow
}
Example Explanation:
The `sound` method is overridden in the `Dog` and `Cat` classes, showing different behavior
depending on the object.
Two Mark Questions
1. What is the difference between var, final, and const keywords used in variable declaration?
2. How do you declare an integer variable and initialize it with a value in Dart?
3. Write a simple expression to check if two strings are equal in Dart.
4. What is the output of the following code: int x = 10; print(x++);
5. What is the purpose of a for loop in Dart?
6. How do you access an element by its index in a list?
7. What is the difference between a Map and a List data structure in Dart?
8. Can you define a class named Person with attributes for name and age?
9. What is the syntax for calling a method on an object instance in Dart?
10. What is the benefit of using named parameters in a function definition?
1. Explain the concept of null safety in Dart. How does it improve code reliability?
2. Compare and contrast if statements and switch statements in Dart. When would you use
each one?
3. Explain the concept of inheritance in Dart using the concept of sub-classes. Provide a
simple example with a base class and a sub-class .
4. Explain the concept of arrow functions in Dart and their benefits.
5. Describe the different types of loops available in Dart
6. Explain the concept of collections in Dart. Briefly discuss the differences between List,
and Map data structures.
7. What are null-safety benefits in Dart compared to languages without it?