0% found this document useful (0 votes)
44 views

Lab 3 1

The document discusses Dart functions, classes, and related concepts: 1. It explains functions, including optional and named parameters, default values, anonymous functions, higher-order functions, closures, and arrow functions. 2. It covers classes, including defining classes, properties, methods, constructors, serialization, and inheritance. 3. It provides examples of defining functions, classes for users, passwords, students, and spheres, as well as using functions with classes.
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)
44 views

Lab 3 1

The document discusses Dart functions, classes, and related concepts: 1. It explains functions, including optional and named parameters, default values, anonymous functions, higher-order functions, closures, and arrow functions. 2. It covers classes, including defining classes, properties, methods, constructors, serialization, and inheritance. 3. It provides examples of defining functions, classes for users, passwords, students, and spheres, as well as using functions with classes.
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/ 21

DART ASSIGNMENT

LAB 03
1) Chepter 5 : Function
// Chepter 5: Functions

/*
void main(List<String> arguments) {
//Function is one small task to used for divide one larger task into
smaller part.
const inp = 12;
final op = compliment(inp);
print(op);

// Making parameters optional


// You can make any parameter optional using [](square) braces.
String fullName(String first, String last, [String? title])
{
if(title == null)
{
return "$title $first $last";
}
else
{
return "%first $last";
}
}

// with all arguments


print(fullName("Ray", "Wnderlich"));
//without optional argument.
print(fullName("Albert", "einstein", "Professor"));

// Providing default values


// You can provid default value by assigning direct values in
function parameter.
bool withTolerance(int value, [int min = 0, int max = 10])
{
return min <= value && value >= max;
}

withTolerance(5); // true.
withTolerance(15); //false
withTolerance(9, 7, 11); //true
//Naming parameters
// you can add naming parameters using {}(curly) braces, but in
naming parameters you must use parameter names when you provide
// their argument values to the function.
bool tolerance(int value, {int min = 0, int max = 10})
{
return min <= value && value >= max;
}

tolerance(9, min:7, max:11);

// named parameters are also optional.


tolerance(5); //true
tolerance(15); //false

// Making named parameters required


bool tol({required int value, int min = 0, int max = 10})
{
return min <= value && value <= max;
}

//tol(); //It will gives error, because value argument is reqired.

//Mini - Exercises
/*1. Write a function named youAreWonderful, with a String
parameter called name. It should return a string using
name, and say something like “You’re wonderful, Bob.” */

String youAreWonderful(String str)


{
return "You are wonderful $str";
}

/*2. Add another int parameter to that function called


numberPeople so that the function returns something
like “You’re wonderful, Bob. 10 people think so.” */

String youAreWonderful2(String str, int num)


{
return "You are wonderful $str, $num people think so";
}

/* 3. Make both inputs named parameters. Make name


required and set numberPeople to have a default of 30.*/
String youAreWonderful3({required String name, int num = 0})
{
return "You are wonderful $name, $num people think so";
}

// Anonymous functions
// Anonymous function is function without name.
// The returned type will be inferred from the return value of the
function body.
int number = 4;
String greeting = "hello";
bool ishungry = true;
Function multiply = (int a, int b)
{
return a * b;
};

print(multiply(3, 2)); // 6

// Passing functions to functions


void namedFunction(Function anoy)
{
//function body
}

// Returning functions from functions


Function applyMul(num mul)
{
return(num val)
{
return val * mul;
};
}

//triple recieves a anoynymous function from this now we can call


triple.
final triple = applyMul(3);
print(triple(6));
print(triple(14.0));

// Above both are called as higher order functions.

//Anoymous functions in forEach loops:


const numbers = [1, 2, 3];

numbers.forEach((number)
{
final tripled = number * 3;
print(tripled);
});

//Closures and Scope


//Anonymous functions are called as clousers.
// The area where we can access the variable called variable's scope.

Function counts()
{
var counter = 0;
final incr = ()
{
counter += 1;
return counter;
};
return incr;
}

final c1 = counts();
final c2 = counts();

print(c1()); // 1
print(c2()); // 1
print(c1()); // 2
print(c1()); // 3

// Mini-exercises :
/* 1. Change the youAreWonderfulfunction in the first mini-
exercise of this chapter into an anonymous function.
Assign it to a variable called wonderful.*/

Function wonderful = ({required String name, int num = 0})


{
return "You are wonderful $name, $num people think so";
};
print(wonderful(name : "Manan", num : 50));

/* 2. Using forEach, print a message telling the people in the


following list that they’re wonderful.*/

const people = ["Chris", "Tiffani", "pablo"];


people.forEach((p)
{
print("$p is wonderful!");
});

//Arrow function
int add(int a, int b) => a + b;

Function applymul(num mul)


{
return (num val) => val * mul;
}

//Mini Exercise
/* Change the forEach loop in the previous “You’re wonderful”
mini-exercise to use arrow syntax.*/
people.forEach((p) => print("$p is wonderful!"));

// Challanges :
/* 1) Prime time*/
bool prime(int n)
{
for (int i = 2; i * i <= n; i++)
{
if(n % i == 0)
{
return false;
}
}
return true;
}

/* Challenge : 2 */
num repeattask(int times, int input, Function task)
{
num ans = 0;
for(int i = 0; i < times; i++)
{
ans += task(input);
}
return ans;
}

Function task = (int num) => num * num;

print(repeattask(4, 2, task));

// Challenge : 3
num repeattask1(int times, int input, Function task)
{
num ans = 0;
for(int i = 0; i < times; i++)
{
ans += task(input);
}
return ans;
}

Function func = (int num) => num * num;

print(repeattask(4, 2, func));

/*
Output :
12 is a very nice number
null Ray Wnderlich
%first einstein
6
18
42.0
3
6
9
1
1
2
3
You are wonderful Manan, 50 people think so
Chris is wonderful!
Tiffani is wonderful!
pablo is wonderful!
Chris is wonderful!
Tiffani is wonderful!
pablo is wonderful!
16
16
*/

}
String compliment(int number)
{
return "$number is a very nice number";
}
*/
2) Chepter 6 : Classes
// Chepter - 6 : Classes
/*
//Defining class

class Myclass{
String prop = "Car";
Myclass([this.prop = "House"]);
}
class User{
late int __pri;
int id = 0; //property
String name = ""; //property

//short-form
//User(this.id, this.name);

//long-form
// User(int id, String name) {
// this.id = id;
// this.name = name;
// }

// User.anonymous()
// {
// id = 0;
// name = 'anoymous';
// }

@override
String toString()
{
return 'User(id : $id, name : $name';
}

String toJson()
{
return '{"id":$id, "name":$name}';
}
}

class Password{
String value = "1234";

@override
String toString()
{
return 'Your password is $value';
}

bool isValid()
{
if(value.length > 8)
{
return true;
}
return false;
}
}

class Student{
final firstName;
final lastName;
int grade;

Student([this.firstName = "", this.lastName = "", this.grade = 0]);


void Print()
{
print("Full name $this.firstName $lastName");
print("Grade : $grade");
}
}

class Sphere{
static const double pi = 3.14285714;
final double radius;

const Sphere({required this.radius})


:assert(radius > 0);

double getVolume()
{
return (4 / 3) * pi * radius * radius * radius;
}

double getSurfaceArea()
{
return 4 * pi * radius * radius;
}
}

class Password1
{
final value;
Password1({required this.value});
}

class MyClass {
var myProperty = 1;
}

/* const User2({int id = 0, String name = "anonymous"})


:assert(id >= 0),
_id = id,
// ignore: unused_element
_name = name;
*/

void main(List<String> arguments) {


// Defining class
// You need to define class outside of main function.
//Creating an object from a class
//final user = User();

// You can also use new


//final user1 = new User();

//Assigning properties
//user.name = "Ray";
//user.id = 42;

//If you put User class below main method then its also works.
//print(user); // print instance of user

// All classes in dart are derived from object, which has a tostring
method.
// @ are called annotations.

//Adding methods
//Serialization is the process of converting a complex data object
into a string.
//Later, when you want to read the data back in, you can do so by way
of deserialization.

//Now add another method in User class that will convert your object
into JSON format.
//print(user.toJson());

//Cascade notation
//final user2 = User();
//user2.name = "Manan";
//user2.id = 42;

//From .. operator you can use multiple assignments on the same


object without having to repeat the object name.
//Semicolon onlu appear in last line.
//final user3 = User()
//..name = "Rahul"
//..id = 31;

// Constructors
// Default
/* class Address {
Address();
var value = '';
} */

/*
Custom
Long-form constructor
This constructor takes two parameters, id and name, and
initializes the corresponding properties of the object.
User(int id, String name) {
this.id = id;
this.name = name;
}
Short-form constructor
This constructor uses the this keyword to automatically
initialize the properties from the constructor parameters.
User(this.id, this.name);
Named constructor: Anonymous User
This constructor creates a user with preset id and name values.

User.anonymous() {
id = 0;
name = 'anonymous';
}

Initializer list with asserts


This constructor takes named parameters and uses assert
statements to check if id is non-negative and name is not empty.

User({int id = 0, String name = 'anonymous'})


: assert(id >= 0),
assert(name.isNotEmpty),
this.id = id,
this.name = name;
JSON serialization method
This method returns a JSON representation of the User object.
String toJson() {
return '{"id": $id, "name": "$name"}';
}

// Overriding toString method


// This method customizes how the User object is printed.
@override
String toString() {
return 'User(id: $id, name: $name)';
}
*/

// Mini - Exercise
// 1. Create a class called Password and give it a string property
called value.
/* class Password{
String value = "1234";
}*/
Password ps = new Password();
print(ps.value);

//2. Override the toString method of Password so that it prints


value.
print(ps.toString);

//3. Add a method to Password called isValid that returns true only
if the length of value is greater than 8.
/*
class Password{
String value = "1234";

// A class to represent a User


class User {
final int id;
final String name;
}
// Generative Constructor with default values for id and name
// You can create a User object by specifying id and name.
// If no id or name is provided, the default values will be used.
const User({this.id = 0, this.name = 'anonymous'}) : assert(id >=
0);

// Named Constructor to create an anonymous User


// It calls the generative constructor with no arguments, creating
an anonymous user.
const User.anonymous() : this();

// Factory Constructor to create a User with specific properties


// This constructor takes a JSON map as input and returns a User
object.
factory User.fromJson(Map<String, Object> json) {
final userId = json['id'] as int;
final userName = json['name'] as String;
return User(id: userId, name: userName);
}

// Method to convert the User object to a JSON string


// It returns a JSON representation of the User object.
String toJson() {
return '{"id":$id,"name":"$name"}';
}

@override
String toString() {
return 'User(id: $id, name: $name)';
}
}
*/
//Mini - exercise
// 1) make value final variable, but not private;
// class Password
// {
// final value;
// Password({required this.value = 0});
// }
// --------------------------------------------------------------------
----------
// Objects
// Objects and References
/*
class MyClass {
var myProperty = 1;
}

//Getters

class UserWithGetters {
// Private fields
final int _id;
final String _name;

// Getters for public access to the fields


// These getters allow external code to access the private fields.
int get id => _id;
String get name => _name;

// Generative Constructor with default values for id and name


const UserWithGetters({this.id = 0, this.name = 'anonymous'}) :
assert(id >= 0);
}
*/

//Calculated Properties
/*
class UserWithCalculatedProperty {
final int _id;

// Constructor with default value for id


// You can create a User object by specifying id.
// If no id is provided, the default value will be used.
const UserWithCalculatedProperty({this.id = 0}) : assert(id >= 0);

// Getter for calculated property


// This getter checks if the id is bigger than 1000 and returns a
boolean value.
bool get isBigId => _id > 1000;
}

//Setters

class EmailWithSetter {
var _address = '';

// Getter for the email address


// This getter returns the email address.
String get value => _address;

// Setter for the email address


// This setter sets the email address with the provided address.
set value(String address) => _address = address;
}
*/

//Singleton Pattern
/*
class MySingleton {
MySingleton._();

// Static instance of the singleton class


static final MySingleton instance = MySingleton._();
}

// ----- Utility Method -----

class MyUtilityClass {
// Static utility method
static void doSomething() {
print('Doing something useful!');
}
}

*/

//Creating New Objects


/*
class UserFromJson {
final int id;
final String name;

// Constructor with default values for id and name


const UserFromJson({this.id = 0, this.name = 'anonymous'});

// Static method to create a User object from a JSON map


// It takes a JSON map as input and returns a User object.
static UserFromJson fromJson(Map<String, Object> json) {
final userId = json['id'] as int;
final userName = json['name'] as String;
return UserFromJson(id: userId, name: userName);
}
}
*/

//Challanges
//1) Challange 1 :
final s1 = Student("Bert", 95);
final s2 = Student("Ernie", 85);
s1.Print();

//2) Spheres :-
const Sphere s = Sphere(radius : 12);
print(s.getVolume());
print(s.getSurfaceArea());

/*
Output :-
1234
Closure: () => String from Function 'toString':.
Full name Instance of 'Student'.firstName 95
Grade : 0
7241.14285056
1810.28571264
*/

}
*/

3) Chepter 7 : Nullability
/// Chapter-7 NULLABILITY
/*
// import 'dart:html';
import 'dart:math';

/**
* Null means "no value" or "absence of a value".
* -A value of type "Null" can't be assigned to a variable of type
'int'
*
*/

class Name{
String giveName;
String surname;
bool surNameIsFirst;
Name(this.giveName, this.surname, this.surNameIsFirst);

@override
String toString()
{
if(surNameIsFirst)
{
return '$surname $giveName';
}
else{
return '$giveName $surname';
}
}
}

void main(List<String> arguments) {

bool isPositive(int anInteger) {


return !anInteger.isNegative;
}

print(isPositive(3));
print(isPositive(-1));

// print(isPositive(null)); //This gives an error.

/*
-Nullable types end with a question mark(?)
-Non-nullable types do not end with a question mark(?)

-Dart types are non-nullable by default.


e.g. int: 3, 1, 7, 4, 5
double: 3.14159265, 0.001, 100.5
bool: true, false
String: "a", "hello", "Would you like fries with that?"
User: ray, vicki, anonymous

int postalCode = null; //error


*/

// Nullable types
/*
-A nullable type can contain the null value in addition to its own
data type.
e.g. int?: 3, null, 1, 7, 4, 5
double?: 0.001, 100.5, null
bool?: true, false, null
String?: "a", "hello", "Would you like fries with that?", null
User?: ray, vicki, anonymous, null
*/

int? age;
double? height;
String? message;

print(age);
print(height);
print(message);

// Mini-exercises
// 1)
String? profession;
print(profession);

// 2)
profession = "basketball player";
print(profession);

//3)
const iLove = "Dart"; // type: String

/*
Handling nullable types
String? name;
print(name.length);

-The property 'length' can't be unconditionally accessed because the


receiver can be "null".
*/

/**
* Type promotion:
* e.g.: String? name;
* name = "Raj";
* print(name.length);
* -Dart promotes the nullable and largely unusable String? type to a
non-nullable String with no extra work.
*
* -Null-aware operators are the operators that can help to handle
potentially null values.
* 1) If-null operator(??)
* -> It is the most convenient way to handle null values.
* -> It says "If the value on the left isn't null, then use it;
otherwise , go eith the value on the right."
* e.g. String? message;
* final text = message ?? "Error";
*
* 2) Null-aware assignment operator(??=)
* -> It is used when there is a single variable that we want to
update if its value is null.
* -> It combines the null check with the assignment.
* e.g. double? fontSize;
* fontSize = fontSize ??= 20.0;
*
* 3) Null-aware access operator(?.)
* -> The Null-aware access operator returns null if the left-hand
sideis null.
* -> Otherwise, itreturns the property on the right-hand side.
* -> The ?. operatoris useful if you want to only perform an
action when the value is non-null.
* -> This allows you to gracefully proceed without crashing the
app.
* -> It is also known as Null-aware method invocation
operator(?.).
* e.g. int? age;
* print(age?.isNegative); // null
*
* 4) Null assertion operator(!)
* -> Also known as bang operator.
* -> If someone is not sure that a variable isn't null, then it
can turn it into a non-nullable type by using this operator.
* e.g. String nonNullableString = myNullableString!;
*
* 5) Null-aware cascade operator(?..)
* -> It allows to call multiple methods or set multiple properties
ont he same object.
* e.g. class User{
* String? name;
* int? id;
* }
* User user = User()
* ?..name = "Ray";
* ..id = 42;
*
* User? user;
* 7) Null-aware index operator(?[])
* -> It is used for accessing the elements of a list when the list
itself might be null.
* e.g. List<int>? myList = [1, 2, 3];
* int? myItem = mYList?[2];
*
* -> Dart requires to initialize any non-nullable member variables
before using them.
* class User{
* String name;
* }
*
* // Using initializers:
* class User{
* String name = "anonymous";
* }
*
* // Using initializing formals:
* class User{
* User(this.name);
* String name;
* }
*
* // Using an initializer list:
* class User{
* User(String name)
* :_name = name;
* String _name;
* }
*
* // Using default parameter values
* class User{
* User([this.name = "anonymous"]);
* String name;
* }
*
* // Required named parameters
* class User{
* User({required this.name});
* String name;
* }
*
* // Nullable instance variables
* class User{
* User({this.name});
* String? name;
* }
*
* // No promotion for non-local variables
* class TextWidget{
* String? text;
* bool isLong(){
* final text = this.text; // shadowing
* if(text == null)
* return false;
* }
* return text.length > 100;
* }
* 8) Null-aware spread operator(---?)
*
*/
bool flowerIsBeautiful = isBeautiful('flower') as bool;

//Challanges
//1) Random nothings :-
int? getRandomNumberOrNull()
{
int? randomValue = Random().nextInt(2);
return randomValue == 1 ? 42 : null;
}
int? res = getRandomNumberOrNull();
print(res);

//2) Naming Customs :-


Name p1 = Name('Alice', '', true);
print(p1);

/*
Output :-
true
false
null
null
null
null
basketball player
null
Alice
*/

bool? isBeautiful(String? item) {


if (item == 'flower')
return true;
else if (item == 'garbage') return false;
return null;
}

/*
The late Keyword:
-Using late means that Dart doesn't initialize the variable .
-It only initializes it when you access it the first time.
-This is also known as lazy initialization.
class User{
User(this.name){
_secretNumber = _calculateSecret();
}
late final int _secretNumber;
}

Dangers of being late:


-We can also use late with non-final variables.
class User{
late String name;
}

Benefits of being lazy:


-When it might take some heavy calculations to initialize a variable.
-If you never end up using the variable, then all that initialization
work was a waste.
-Top-level and static variables have always been lazy in Dart.
*/
*/

You might also like