Lab 3 1
Lab 3 1
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);
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;
}
//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.” */
// 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
numbers.forEach((number)
{
final tripled = number * 3;
print(tripled);
});
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.*/
//Arrow function
int add(int a, int b) => a + b;
//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;
}
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;
}
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;
class Sphere{
static const double pi = 3.14285714;
final double radius;
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;
}
//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;
// 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';
}
// 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);
//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";
@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;
//Calculated Properties
/*
class UserWithCalculatedProperty {
final int _id;
//Setters
class EmailWithSetter {
var _address = '';
//Singleton Pattern
/*
class MySingleton {
MySingleton._();
class MyUtilityClass {
// Static utility method
static void doSomething() {
print('Doing something useful!');
}
}
*/
//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';
}
}
}
print(isPositive(3));
print(isPositive(-1));
/*
-Nullable types end with a question mark(?)
-Non-nullable types do not end with a question mark(?)
// 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);
/**
* 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);
/*
Output :-
true
false
null
null
null
null
basketball player
null
Alice
*/
/*
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;
}