Unit - 1
Unit - 1
Introdution to Dart
Introduction to Dart
What is Dart ?
void main() {
print("Hello World");
}
Output :
Hello World
Program 2 :
void main() {
print(4);
}
Program 3 :
void main() {
print(4-2);
}
Program 4:
void main() {
print(false);
}
Comments in Dart
Program 5 :
// this is my first line of code
void main() {
print("Hello World");
}
Program 6 :
void main() {
print("Hello World"); // this is my first line of code..
}
Exploring Data Types and Variables
➢How to declare a variable
➢What are built-in data Types in Dart?
➢What are Literals?
➢String Interpolations
➢Constants in Dart
1.final keyword
2.const keyword
Built-in data Types in Dart
Dart has special support for these data types
1.Numbers
->Int
->double
2.Strings
3.Booleans
4.Lists(also Known as arrays)
5.Maps
6.Runes(for expressing Unicode characters in a String)
7.Symbols
bool isAlive=true;
Or
var isAlive=true;
void main() {
}
Strings, Literals and String Interpolation
➢Literals :
Literals in Dart are a synthetic representation of boolean, character, numeric,
or string data.
➢String Interpolation
Literals :
void main() {
//Literals
int age = 2;
String sem ="6th sem C Sec";
bool isValid = true;
print(age);
print(sem);
print(isValid);
}
void main() {
String s1 = 'hanu';
String s2 = "hanu";
String s3 = 'It\'s apple';
print(s1);
print(s2);
print(s3);
}
void main(){
String msg = " I am Hanu " + "I am handling HAD Subject for 6th Sem";
print(msg);
}
void main() {
//String Interpolation
print(message);
}
void main() {
//String Interpolation
}
void main() {
//String Interpolation
}
void main() {
//string interpolation
//String interpolation
}
Integer Interpolation :
void main() {
var l=10;
var b=20;
print("length of l and b is ${l+b}");
}
void main() {
var l=10;
var b=20;
print("length of $l and $b is ${l+b}");
}
bool Datatype
void main(){
bool isLoggedIn=false;
if(isLoggedIn){
print("Welcome");
}else{
print("Please login");
}
}
Defining Constants :
Keywords are :
• final
• const
if you never want to change a value then use final and const keywords
Ex :
final name =“Hanu”;
const PI = 3.14;
Difference between final and const
final variable can only be set once and it is initialized when accessed.
const variable is implicitly final but it is a compile time constant
- i.e it is initialized during compilation
Set
1.HashSet
Maps
1.HashMap
List
-> in Dart, ARRAY is known as LIST
->Elements are stored in ordered collection
Two types :
Fixed – length list : Length once defined cannot be changed.
Growable list – length is dynamic
Fixed length
void main() {
List<int> number = List.filled(3,0);
number[0]=20;
number[1]=30;
number[2]=40;
print(number[1]);
}
Growable List
void main(){
List<String> fruits =[];
fruits.add("apple");
fruits.add("cherry");
print(fruits);
}
Accessing List Elements
void main() {
var names = ['Alice', 'Bob', 'Charlie'];
void main() {
var numbers = [1, 2, 3];
void main() {
var cities = ['New York', 'London', 'Paris'];
print(languages.length); // Output: 3
}
List Methods
Set in dart
A Set in Dart is an unordered collection of unique items. Unlike Lists, Sets do not allow
duplicate values.
void main() {
// Using Literal
Set<int> numbers = {1, 2, 3, 4, 5};
print(numbers); // Output: {1, 2, 3, 4, 5}
fruits.add('orange');
print(fruits);
fruits.remove('apple');
print(fruits);
}
Adding Elements to a Set
void main() {
var colors = {'Red', 'Green'};
print(items.length); // Output: 4
}
Converting a List to a Set (Removing
Duplicates)
void main() {
List<int> numbers = [1, 2, 2, 3, 4, 4, 5];
1.Creating Maps
void main() {
// Using Literal
Map<String, int> ages = {
'Alice': 25,
'Bob': 30,
'Charlie': 28,
};
print(ages);
}
2. Using Map Constructor
void main() {
var students = Map<String, String>();
students['101'] = 'John';
students['102'] = 'Emma';
print(students); // Output: {101: John, 102: Emma}
}
Accessing Values
void main() {
Map<String, String> countries = {'USA': 'Washington', 'India': 'New Delhi'};
void main() {
var fruits = {'apple': 1, 'banana': 2, 'cherry': 3};
void main(){
myFunction(); //Calling the function
}
myFunction(){ //function definition
print("hello");
}
Output :
2. Function with Parameters
Example: Function with Required Parameters
void sayHello(String name){
print("Hello $name");
}
void main(){
sayHello("Hanu");
}
Function with Default Parameters
void sayHello(String name, {String title ="Mr/Ms"} ){
print("Hello $title $name");
}
void main(){
sayHello("Hanu");
}
Function with named parameter
void introduce({String? name,int? age}){
print("Name : $name,Age : $age");
}
void main(){
introduce(name :"Hanu",age:30);
introduce(age:32,name:"naveen");
}
Function Returning a Value
int add(int a , int b){
return a+b;
}
void main(){
int sum=add(3,5);
print(sum);
}
Arrow Function (Short Syntax)
int multiply(int a, int b) => a * b;
void main() {
print(multiply(4, 5)); // 20
}
Operators
1. Arithmetic Operators
2. Assignment Operators
3. Relational (Comparison) Operators
4. Logical Operators
5. Bitwise Operators
6. Type Test Operators
7. Conditional (Ternary) Operator
8. Null-aware Operators
1. Arithmetic Operators
2. Assignment Operators
3. Relational (Comparison) Operators
4. Logical Operators
5. Bitwise Operators
6. Type Test Operators
7. Conditional (Ternary) Operator
8. Null-aware Operators
Control flow statements
1. Conditional Statements :
Conditional statements allow decision-making based on conditions.
(a) if Statement
Executes a block of code if a condition is true.
Ex :
void main() {
int num = 10;
if (num > 5) {
print("Number is greater than 5");
}
}
(b) if-else Statement
Executes different blocks of code based on a condition.
Ex :
void main() {
int num = 3;
if (num > 5) {
print("Number is greater than 5");
} else {
print("Number is 5 or less");
}
}
(c) if-else if-else Statement (Nested if)
Used when multiple conditions need to be checked.
Ex :
void main() {
int marks = 85;
switch (day) {
case 1:
print("Monday");
break;
case 2:
print("Tuesday");
break;
case 3:
print("Wednesday");
break;
default:
print("Invalid day");
}
}
2. Looping Statements
Loops help execute code multiple times.
(a) for Loop
• Used when the number of iterations is known.
void main() {
for (int i = 1; i <= 5; i++) {
print("Iteration $i");
}
}
(b) while Loop
Executes as long as a condition is true.
Example :
void main() {
int i = 1;
while (i <= 5) {
print("Iteration $i");
i++;
}
}
(c) do-while Loop :
Similar to while, but ensures execution at least once.
void main() {
int i = 1;
do {
print("Iteration $i");
i++;
} while (i <= 5);
}
3. Jump Statements
Jump statements control the loop execution flow.
(a) break Statement
Used to exit a loop or switch statement.
EX :
void main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break; // Stops loop at i == 3
}
print(i);
}
}
(b) continue Statement
Skips the current iteration and moves to the next.
Ex :
void main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skips iteration when i == 3
}
print(i);
}
}
Exceptions in Dart
In Dart, exceptions are runtime errors that occur when a program encounters
an unexpected situation.
such as dividing by zero, accessing an invalid index in a list, or failing to open
a file.
Dart provides a structured way to handle such errors using exception handling
mechanisms.
1. Throwing Exceptions
You can explicitly throw an exception using the throw keyword.
Example: Throwing an Exception
void main() {
try {
int result = 10 ~/ 0;
print(result);
} catch (e) {
print("Exception: $e");
} finally {
print("Execution completed.");
}
}
Combining try, on, catch, finally
Example :
void main() {
try {
int result = 10 ~/ 0; // Throws an UnsupportedError
print(result);
} on UnsupportedError {
print('Cannot divide by zero.');
} catch (e) {
print('An error occurred: $e');
} finally {
print('Execution completed.');
}
}
Class
In Dart, classes are the foundation of object-oriented programming (OOP). A
class defines the blueprint for creating objects, encapsulating data (fields) and
behavior (methods).
A constructor is a special type of method used in object-oriented
programming to initialize objects. It is automatically called when an instance of
a class is created.
Key Points:
• In many programming languages, a constructor has the same name as the
class.
• It often doesn’t have a return type.
class Car {
String brand = "Toyota"; // Property
void drive() { // Method
print(" I am driving car.");
}
}
void main() {
var myCar = Car(); // Creating an object
print(myCar.brand); // Output: Toyota
myCar.drive(); // Output: I am driving car.
}
1. Defining a Class and Creating an Object
class Person {
// Fields (Instance default Variables)
String name = “Tejas";
int age = 25;
// Method
void displayInfo() {
print("Name: $name, Age: $age");
}
}
void main() {
// Creating an object
Person p1 = Person();
p1.displayInfo();
}
class Car{
String brand;
int number;
//Constructor
Car(this.brand,this.number);
//method
void display(){
print("Brand : $brand,Number:$number");
}
}
void main(){
var b1=Car("honda",1234);
b1.display();
}
void showDetails() {
print("Brand: $brand, Model: $model");
}
}
void main() {
var car1 = Car("Ford", "Mustang");
car1.showDetails(); // Output: Brand: Ford, Model: Mustang
void main() {
BankAccount acc = BankAccount();
acc.balance = 1000; // Setting value
print(acc.balance); // 1000
}
Inheritance :
class Animal {
void makeSound() {
print("Some sound...");
}
}
void main() {
Dog dog = Dog();
dog.makeSound(); // Some sound...
dog.bark(); // Woof! Woof!
}
Named & Default constructor
class Car {
String brand;
int year;
// Default constructor
Car(this.brand, this.year);
// Named constructor
Car.fromOldModel(this.brand) {
year = 2000; // Default year for old models
}
void display() {
print("Brand: $brand, Year: $year");
}
}
void main() {
var car1 = Car("Toyota", 2023); // Using default constructor
var car2 = Car.fromOldModel("Honda"); // Using named constructor
void sayHello() {
print("Hello from my_library!");
}
Step 2: Import and Use It (main.dart)
import 'my_library.dart';
void main() {
sayHello(); // Output: Hello from my_library!
}
Package Libraries
Dart allows you to use external libraries (packages) from pub.dev.
Steps to Use a Package Library :
Step 1: Add Dependency in pubspec.yaml
yaml
dependencies:
http: ^0.13.0
Step 2: Import and Use the LibrarydartCopyEdit
void main() {
print(pi); // Allowed
// print(sqrt(16)); Error: sqrt() is not imported
}
Example: Using hide
import 'dart:math' hide pi;
void main() {
print(sqrt(16)); // Allowed
// print(pi); Error: pi is hidden
}
Visibility
In Dart, visibility refers to the accessibility of class members (fields, methods,
constructors) within and outside a library.
Unlike some other languages that use keywords like public, private, or
protected, Dart uses library-based visibility and relies on underscores (_) to
indicate private members.
1. Public Members (Default)
By default, all classes, methods, and fields in Dart are public. This means they are
accessible from anywhere, including other files and libraries.
class MyClass {
int publicVar = 10; // Accessible anywhere
void display(){
print("value of : $publicVar");
}
}
void main() {
MyClass c1=MyClass();
c1.display();
}
2. Private Members (_ underscore)
In Dart, members (fields, methods, constructors) that start with an underscore
(_) are private to the library they are declared in.
class MyClass {
int _privateVar = 20; // Private, accessible only within the same library
void _privateMethod() {
print("Private Method");
}
}
Accessing Private Members (Same Library)
class MyClass {
int _privateVar = 20; // Private, accessible only within the same library
void _privateMethod() {
print("Private Method");
}
}
void main() {
var obj = MyClass();
print(obj._privateVar); // Allowed (same library)
obj._privateMethod(); // Allowed (same library)
}
Using part and part of for Shared Visibility
If you want to split a Dart library into multiple files while keeping private
members accessible, use part and part of.
library my_library;
part 'part_file.dart';
class MyClass {
String _privateVar = "This is private";
}
part of my_library;
void main() {
num x = 10;
int y = x as int; // Explicit casting
print(y); // Output: 10
}
2.Using is to Check Type Before Casting
void main() {
num x = 10;
if (x is int) {
int y = x; // Safe cast
print(y);
}
}
3.Using is! to Check If Not a Certain Type
void main() {
num x = 10;
if (x is! int) {
print("x is not an integer");
}
else{
print('x is an integer');
}
}
4.Converting String to Number (int.parse / double.parse)
void main() {
String Str = "123";
int number = int.parse(Str);
double decimalNumber = double.parse("123.45");
void main() {
int num = 100;
String str = num.toString();
void main() {
int x = 10;
double y = x.toDouble(); // Convert int to double
print(y); // Output: 10.0
double z = 10.9;
int w = z.toInt(); // Convert double to int
print(w); // Output: 10
}
Raw String
void main() {
String s1= "Hello\nWorld"; // Interprets \n as a newline
String s2 = r"Hello\nWorld"; // Treats \n as plain text
print(s1); // Output:
// Hello
// World
print(s2); // Output: Hello\nWorld
}
Collections ( refer List,Set & Map concepts)