0% found this document useful (0 votes)
0 views122 pages

Unit - 1

Dart is an open-source, general-purpose programming language developed by Google, primarily used for building high-performance applications across web, mobile, and desktop platforms, especially with Flutter. Key features include its compiled nature, object-oriented design, type safety, and support for asynchronous programming, making it efficient and easy to learn. The document covers fundamental concepts such as data types, variables, collections, functions, and operators in Dart programming.

Uploaded by

mainak2003patra
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)
0 views122 pages

Unit - 1

Dart is an open-source, general-purpose programming language developed by Google, primarily used for building high-performance applications across web, mobile, and desktop platforms, especially with Flutter. Key features include its compiled nature, object-oriented design, type safety, and support for asynchronous programming, making it efficient and easy to learn. The document covers fundamental concepts such as data types, variables, collections, functions, and operators in Dart programming.

Uploaded by

mainak2003patra
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/ 122

Unit - 1

Introdution to Dart
Introduction to Dart
What is Dart ?

➢Dart is an open-source, general-purpose programming language


developed by Google.
➢ It is designed for building high-performance applications, especially
for web, mobile, and desktop platforms.
➢Dart is the primary language used in Flutter, Google's UI toolkit for
building natively compiled applications for mobile, web, and desktop
from a single codebase.
Key Features of Dart
Compiled Language – Dart supports both Just-in-Time (JIT) compilation
for faster development and Ahead-of-Time (AOT) compilation for
optimized performance.
Object-Oriented – Dart is an object-oriented language with support for
classes, inheritance, and interfaces.
Type Safe – It uses static and dynamic typing, ensuring type safety
while allowing flexibility.
• Garbage Collection – Dart has automatic memory management,
making it efficient for app development.
• Concurrency Support – Uses async and await keywords for handling
asynchronous programming.
• Cross-Platform – Write once, run anywhere—Dart applications can
run on mobile (iOS & Android), web, desktop, and embedded devices.
• Fast Development with Hot Reload – When used with Flutter, Dart
supports hot reload, enabling developers to see instant updates.
Why use Dart?
Perfect for Flutter Development – If you’re building mobile apps with
Flutter, Dart is the go-to language.
Easy to Learn – Dart’s syntax is clean and familiar to those with
experience in Java, JavaScript, or C#.
Fast Execution – The AOT compilation makes Dart applications run
efficiently.
Great Tooling Support – Supported by VS Code, Android Studio, and
IntelliJ IDEA.
Getting started with dart programming
Program 1 :

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

Note – All data types in Dart are Objects


Therefore, values are by default null
Variable declaration
int age =10;
Or
var age = 10;

String name = “Hanu”;


Or
var name = “Hanu;

bool isAlive=true;
Or
var isAlive=true;
void main() {

var hexValue = 0xEAEBEEAD;


print(hexValue);

bool isAlive = true;


print(isAlive);

var exponent = 1.45e5;


print (exponent);

}
Strings, Literals and String Interpolation
➢Literals :
Literals in Dart are a synthetic representation of boolean, character, numeric,
or string data.

➢Various ways to define String Literals in Dart

➢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() {

//Various way to define String Literals

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

String name = "hanu";


String message = "my name is " + name;

print(message);
}
void main() {

//String Interpolation

String name = "Hanu";


String message = "my name is $name";
print(message);

}
void main() {

//String Interpolation

String name = "Hanu";


print("my name is $name");

}
void main() {
//string interpolation

String name = "Hanu";


print("my name is $name");
print("length of name " + name.length.toString());
}
Or
void main() {

//String interpolation

String name = "Hanu";


print("my name is $name");
print("length of name ${name.length}");

}
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

- Instance variable can be final but cannot be const


- If you want a constant at class level then make it static const
Exploring collections in Dart
List :
Different types of List :
1.Fixed – length list
2.Growable list

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'];

print(names[0]); // Output: Alice


print(names.elementAt(1)); // Output: Bob
}
Modifying a List
void main() {
var colors = ['Red', 'Green', 'Blue'];

colors[1] = 'Yellow'; // Modifying element


print(colors); // Output: [Red, Yellow, Blue]
}
Adding Elements to a List
Using add() and addAll()

void main() {
var numbers = [1, 2, 3];

numbers.add(4); // Adds a single element


numbers.addAll([5, 6, 7]); // Adds multiple elements

print(numbers); // Output: [1, 2, 3, 4, 5, 6, 7]


}
Using insert() and insertAll()
void main() {
var numbers = [1, 2, 4, 5];

numbers.insert(2, 3); // Inserts 3 at index 2


numbers.insertAll(4, [6, 7]); // Inserts multiple elements at index 4

print(numbers); // Output: [1, 2, 3, 4, 5, 6, 7]


}
Removing Elements from a List
void main() {
var fruits = ['Apple', 'Banana', 'Cherry', 'Date'];

fruits.remove('Banana'); // Removes 'Banana'


fruits.removeAt(1); // Removes element at index 1 ('Cherry')
fruits.removeLast(); // Removes the last element ('Date')

print(fruits); // Output: [Apple]


}
Checking if an Element Exists

void main() {
var cities = ['New York', 'London', 'Paris'];

print(cities.contains('London')); // Output: true


print(cities.contains('Tokyo')); // Output: false
}
Iterating Over a List
void main() {
var animals = ['Cat', 'Dog', 'Elephant'];

animals.forEach((animal) => print(animal));


}
//output
Cat
Dog
Elephant
Sorting a List
void main() {
var numbers = [5, 2, 8, 1, 9];

numbers.sort(); // Sorts in ascending order


print(numbers); // Output: [1, 2, 5, 8, 9]
}
Getting List Length
void main() {
var languages = ['Dart', 'Java', 'Python'];

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}

// Using Set Constructor


var fruits = Set<String>();
fruits.add('Apple');
fruits.add('Banana');
fruits.add('Cherry');
print(fruits); // Output: {Apple, Banana, Cherry}
}
Set
void main(){
// using literals
Set<String> fruits ={'apple','banana','mango'};
print(fruits);

fruits.add('orange');
print(fruits);

fruits.remove('apple');
print(fruits);
}
Adding Elements to a Set
void main() {
var colors = {'Red', 'Green'};

colors.add('Blue'); // Add single element


colors.addAll({'Yellow', 'Purple'}); // Add multiple elements

print(colors); // Output: {Red, Green, Blue, Yellow, Purple}


}
Removing Elements from a Set
void main() {
var animals = {'Cat', 'Dog', 'Elephant', 'Tiger'};

animals.remove('Dog'); // Remove a specific element

print(animals); // Output: {Cat, Elephant, Tiger}


}
Checking if an Element Exists
void main() {
var numbers = {10, 20, 30, 40};

print(numbers.contains(20)); // Output: true


print(numbers.contains(50)); // Output: false
}
Set Operations (Union, Intersection,
Difference)
void main() {
var setA = {1, 2, 3, 4, 5};
var setB = {4, 5, 6, 7, 8};

print(setA.union(setB)); // Union: {1, 2, 3, 4, 5, 6, 7, 8}


print(setA.intersection(setB)); // Intersection: {4, 5}
print(setA.difference(setB)); // Difference: {1, 2, 3}
}
Checking the length of a Set
void main() {
var items = {100, 200, 300, 400};

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];

Set<int> uniqueNumbers = numbers.toSet();

print(uniqueNumbers); // Output: {1, 2, 3, 4, 5}


}
Clearing a Set
void main() {
var data = {10, 20, 30};

data.clear(); // Removes all elements


print(data); // Output: {}
}
Checking if a Set is Empty
void main() {
var mySet = <String>{};

print(mySet.isEmpty); // Output: true


print(mySet.isNotEmpty); // Output: false
}
Maps in Dart
In general, a map is an object that associates keys and values. Dart support for maps
is provided by map literals and the Map type

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'};

print(countries['India']); // Output: New Delhi


print(countries['USA']); // Output: Washington
}
Adding and Updating Entries
void main() {
var student = {'name': 'Alice', 'age': 20};

// Adding a new key-value pair


student['grade'] = 'A';

// Updating an existing value


student['age'] = 21;

print(student); // Output: {name: Alice, age: 21, grade: A}


}
Removing Entries
void main() {
var products = {'Laptop': 1000, 'Phone': 700, 'Tablet': 500};

products.remove('Phone'); // Remove entry with key 'Phone'

print(products); // Output: {Laptop: 1000, Tablet: 500}


}
Checking if a Key or Value Exists
void main() {
var cities = {'New York': 'USA', 'London': 'UK', 'Paris': 'France'};

print(cities.containsKey('London')); // Output: true


print(cities.containsValue('Germany')); // Output: false
}
Getting All Keys or Values

void main() {
var fruits = {'apple': 1, 'banana': 2, 'cherry': 3};

print(fruits.keys); // Output: (apple, banana, cherry)


print(fruits.values); // Output: (1, 2, 3)
}
Map with Different Data Types
void main() {
var mixedData = {
'name': 'John',
'age': 30,
'isStudent': false,
'scores': [85, 90, 78]
};

print(mixedData['name']); // Output: John


print(mixedData['scores']); // Output: [85, 90, 78]
}
Map of Maps (Nested Maps)
void main() {
var users = {
'user1': {'name': 'Alice', 'age': 25},
'user2': {'name': 'Bob', 'age': 30}
};

print(users['user1']?['name']); // Output: Alice


}
Functions
1.Define a function
2.Pass parameters to a function
3.Return Value from a function
Declaring a Function
A Dart function is defined using the
Syntax :
returnType functionName(parameters) { ... }

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;

if (marks >= 90) {


print("Grade: A");
} else if (marks >= 75) {
print("Grade: B");
} else if (marks >= 50) {
print("Grade: C");
} else {
print("Grade: F");
}
}
(d) Ternary Operator (? :)
A shorthand for if-else conditions
Ex :
void main() {
int a = 10, b = 5;
String result = (a > b) ? "A is greater" : "B is greater";
print(result);
}
(e) switch-case Statement
Used when multiple conditions depend on a single variable.
void main() {
int day = 3;

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 marks(int marks){


if(marks<40){
throw Exception("Marks must be more than 40");
}
print(“Student is Passed");
}
void main(){
marks(39);
}
2. Handling Exceptions (try-on-catch-finally)
Syntax :
try {
// Code that may throw an exception
} on SpecificExceptionType {
// Handle a specific exception
} catch (e) {
// Handle any exception
} finally {
// Code that will always run (optional)
}
Using try-catch
void main() {
try {
int result = 10 ~/ 0; // Division by zero
print(result);
} catch (e) {
print("Exception caught: $e");
}
}
Using on for Specific Exceptions :
Ex :
void main() {
try {
int result = 10 ~/ 0;
print(result);
} on UnsupportedError {
print("Cannot divide by zero.");
}
}
Using finally

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

var car2 = Car.electric();


car2.showDetails(); // Output: Brand: Tesla, Model: Model S
}
Encapsulaton (Getters & Setters)
class BankAccount {
double _balance = 0.0; // Private variable

double get balance => _balance; // Getter

set balance(double amount) { // Setter


if (amount >= 0) {
_balance = amount;
} else {
print("Invalid amount");
}
}
}

void main() {
BankAccount acc = BankAccount();
acc.balance = 1000; // Setting value
print(acc.balance); // 1000
}
Inheritance :
class Animal {
void makeSound() {
print("Some sound...");
}
}

class Dog extends Animal {


void bark() {
print("Woof! Woof!");
}
}

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

car1.display(); // Output: Brand: Toyota, Year: 2023


car2.display(); // Output: Brand: Honda, Year: 2000
}
Libraries and Visibility
A Dart library is a collection of related code elements such as classes, functions,
and variables. Dart supports 4 types of libraries:

Types of Libraries in Dart


Dart provides four main types of libraries:

• Built-in Libraries (predefined in Dart)


• User-defined Libraries (created by developers)
• Package Libraries (third-party packages from pub.dev)
• Dart Core Library (automatically available)
a. Built-in Libraries :
Dart provides several built-in libraries that you can import using the dart: prefix.
Examples include:

dart:core → Automatically imported, contains core functionality (print(), int,


String, etc.)
dart:io → For file, network, and I/O operations
dart:math → Provides mathematical functions (pi, sqrt())
dart:convert → Used for encoding and decoding JSON
dart:async → Supports asynchronous programming (Future, Stream)
Ex :
import "dart:math";
void main(){
print(sqrt(25));
}
User-defined Libraries
Step 1: Create a Library File (my_library.dart)
// my_library.dart
library my_library; // Defining the library

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

import 'package:http/http.dart' as http;

void main() async {


var response = await
http.get(Uri.parse('https://jsonplaceholder.typicode.com/todos/1'));
print(response.body);
}
Dart Core Library
Dart Core Library (dart:core) is automatically available.
No need to import it manually.

Examples of dart:core FunctionsdartCopyEdit


void main() {
print("Hello, Dart!"); // print() from dart:core
int number = 42; // int from dart:core
List<int> numbers = [1, 2, 3]; // List from dart:core
}
Show & Hide in Libraries
Example: Using show
import 'dart:math' show pi;

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 printPrivateVar(MyClass obj) {


print(obj._privateVar); // Allowed because it's the same library
}
Type Casting in Dart : Number,String
1.Using as for Explicit Casting

The as keyword is used to cast an object to a specific type.

void main() {
num x = 10;
int y = x as int; // Explicit casting
print(y); // Output: 10
}
2.Using is to Check Type Before Casting

The is keyword checks if an object is of a specific type.

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

The is! operator checks if an object is NOT of a specific 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");

print(number); // Output: 123


print(decimalNumber); // Output: 123.45
}
5.Converting Number to String (toString)

void main() {
int num = 100;
String str = num.toString();

print(str); // Output: "100"


}
6.Using toDouble() and toInt() for Numeric Conversion

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)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy