This commit is contained in:
nm1 2026-11-04 00:33:23 +05:30
commit 74ae93a96e
5 changed files with 94691 additions and 0 deletions

View file

@ -0,0 +1,125 @@
Basics 2
**for-in loop and foreach loop** : used with collections
```dart
void main() {
var no = [1, 2, 3]; // no here is list which is a collection
// For-in loop
for (var x in no) {
print(x);
}
// foreach
no.forEach((n) => print(n));
}
```
 
**Collections**
- Even if we dont mention collection name and use var instead then due to type inference variable will be converted to that collection.
- List can contain values of different data type. To make sure list contains values of one datatype only, use this `List<datatype>` . eg : `List<String>`
- To make list immutable use const keyword before list.
- When we assign a list to other variable reference is copied. so to make a deep copy use spread operator
```dart
void main() {
// List
List name = ['Rishav', 'Ramesh', 10];
name[1] = 'Suresh';
print(name); // outputs : [Rishav, Suresh, 10]
for (var i in name) {
print(i);
}
List<String> name2 = ['Rishav', 'Bharghav'];
print(name2);
List name3 = const ['Rishav', 'Raghav'];
name3[1] = 'as'; // will give error : Cannot modify an unmodifiable list
print(name3);
var name4 = name; // shallow copy
var name5 = [...name]; //deep copy
name[2] = 12;
print('name4: $name4'); // Output: name4: [Rishav, Suresh, 12]
print('name5: $name5'); // Output: name5: [Rishav, Suresh, 10]
// Sets
Set elements = {'hydrogen', 'oxygen', 'hydrogen'};
print(elements); // Output: {hydrogen, oxygen}
print(elements.runtimeType); // Output: _Set<dynamic>
// ways to make set con
var elements2 = <String>{};
Set<String> elements3 = {};
// both elements2 and elements3 have same runtimeType
print(elements3.runtimeType); // Output: _Set<String>
// Maps
var elements4 = {};
print(elements4.runtimeType); // Output: _Map<dynamic, dynamic>
var student = {'name': 'Rishav', 'age': 20, 'email': 'rishav@email.com'};
print(student.runtimeType); // Output: _Map<String, Object>
}
```
&nbsp;
**Functions**
- dart provides shorthand version of functions too to avoid need for return statment. useful for writing pure functions.
- by default arguments are called positional arguments so order of values in arguments is necessary but with named arguments we can change the order as we have to provide name ie parameter variable at left side.
- there are anonymous functions too like in js
```dart
void main() {
// Functions
print(sum('Rishav', ' Kumar')); //Output: Rishav Kumar
print(sum2(1, 2)); //Output: 3
print(sum3(n2: 'Kumar', n1: 'Rishab')); //Output: RishabKumar
}
dynamic sum(var n1, var n2) {
return n1 + n2;
}
// anonymous function
var f=(){
return 2;
};
or
var f=()=> 2;
// positional arguments
dynamic sum2(var n1, var n2) => n1 + n2;
// named arguments
dynamic sum3({var n1, var n2}) => n1 + n2;
```
&nbsp;
**More about Lists**
```dart
void main(){
List<Map<String, Object>> list = [
{'string': 'Strength', 'amount': 3},
{'string': 'Sugar', 'amount': 3}
];
List<Object?> lis= list.map((e)=> e["string"] ).toList();
print(lis);
print(list.map((e)=> e["string"] ));
}
```

View file

@ -0,0 +1,288 @@
Basics 3 Classes
**Classes and Objects**
- in dart there is no constructor overloading so instead named constructor have to be used.
```dart
class Point {
int? x;
int? y;
// Default constructor
Point() {
x = 0;
y = 0;
}
// named constructor
Point.paramed(int x, int y) {
this.x = x;
this.y = y;
}
// String interpolation
void printData() => print('$x + $y');
// functions
final void Function() onPressed;
}
void main() {
Point p = Point();
print(p.x);
Point p2 = Point.paramed(2, 3);
print(p2.x);
p.printData();
}
```
&nbsp;
**Classes and enums**
- Intead of initializing data members inside block of constructor we can define them in initializer list too as it improves performance too
- we cant use some operators bcz of some null safety measures introdued in dart so use like this `assert(x!=null && x > 0)`
- For Getter and setters , we have keywords too
```dart
class Point {
int? x;
int? y;
// Default constructor
Point() {
x = 0;
y = 0;
}
// named constructor
Point.paramed(int x, int y) {
this.x = x;
this.y = y;
}
// or
Point.paramed2(this.x, this.y);
// or
Point.paramed3(this.x, this.y) : assert(x != null && x > 0) {
printData();
}
Point.fromMap(Map<String, int> map) {
this.x = map['x'];
this.y = map['y'];
}
Point.fromMap2(Map<String, int> map)
: x = map['x'],
y = map['y'] {
printData();
}
// String interpolation
void printData() => print('$x + $y');
void printData2() {
print('$x - $y');
}
// getters
int? get pointX => this.x;
int? get pointY => this.y;
Map<String, int?> get getMap => <String, int?>{
'x': this.x,
'y': this.y,
};
// setters
set setX(int x) => this.x = x;
}
void main() {
Point p = Point();
print(p.x);
Point p2 = Point.paramed(2, 3);
print(p2.x);
p.printData();
p.printData2();
Point p3 = Point.fromMap(<String, int>{
'x': 10,
'y': 20,
});
p3.printData();
Point p4 = Point.fromMap2(<String, int>{
'x': 10,
'y': 20,
});
print(p3.pointX);
print(p3.pointY);
print(p3.getMap);
p.setX = 500;
p.printData();
}
```
Enums
- Enum is special variable which contains fixed number of constant values
```dart
enum PaymentStatus { notPaid,paid };
void main() {
final status = PaymentStatus.notPaid;
switch (status) {
case PaymentStatus.notPaid:
print(1);
break;
default:
8;
}
}
```
&nbsp;
**Exceptional Handling**
- Infinity is a constant which is of double type
- To avoid typecasting automatically use tilt symbol before operator. eg : `var c2 = a ~/ b`
- Multiple catch can be used too for different types of exception too using `on <ExceptionName>`
```dart
// Custom Exception
class AgeException implements Exception {
String errMsg() => 'Age cannot be less than zero';
}
void main() {
print('programming knowledge');
try {
var a = 10;
var b = 0;
var c1 = a / b; // Output : Infinity
// var c2 = a ~/
// b; // Will give Error for unhandled exception : IntegerDivisionByZeroException
print('c1: $c1');
// print('c2: $c2');
var s = [1, 2, 3, 4];
print(s[2]);
var age = -10;
if (age < 0) {
throw AgeException();
}
} on AgeException catch (e) {
print(e.errMsg());
} on IntegerDivisionByZeroException catch (e) {
print('Division of zero isnt possible: ${e.message}');
} catch (e) {
print('Another catch block');
} finally {
print('always executed');
}
}
```
&nbsp;
Async and await
- Future is just like promise in javascript and contains result of asyncronous operation which have 2 states ie completed and uncompleted. and if completed then its data is either some value or error.
```dart
Future<void> fetchUserData() {
return Future.delayed(Duration(seconds: 2), () => print('Data'));
}
void main() {
fetchUserData();
print('Fetching user data');
}
```
- async functions always returns Future datatype. async keyword will always be between closing parenthesis and opening curly braces
- If we dont use await or then we will get instance of the future not the result. if we use then it will assign callback for the result and switch to next line and if we use await then it will wait for result then move to next line.
```dart
Future<String> fetchUserData() {
return Future.delayed(Duration(seconds: 2), () => 'Data');
}
Future<String> fetchUserData2() {
return Future.delayed(Duration(seconds: 4), () => 'Data2');
}
Future<String> userMsg() async {
var data = await fetchUserData();
return '$data';
}
Future<String> userMsg2() async {
var data = await fetchUserData2();
return '$data';
}
void main() async {
print('Fetching');
// total time will be of 6s
print(await userMsg());
print(await userMsg2());
// total time will be of 4s
userMsg().then((value) => print(value));
userMsg2().then((value) => print(value));
// their output will be "Instance of 'Future<String>' "
print(userMsg());
print(userMsg2());
}
```
&nbsp;
**Functions**
In Dart, `function` (lowercase 'f') refers to a specific, named block of code that performs a task. `Function` (uppercase 'F') refers to the general *type* of functions. Think of it like the difference between a specific car (e.g., a "Honda Civic") and the general concept of a "car."
Here's a breakdown:
**1. `function` (lowercase):**
* Represents a named, callable block of code.
* Used when defining or calling a specific function.
```dart
// Defining a function called 'myFunction'
void myFunction() {
print('Hello from myFunction');
}
// Calling the function
myFunction(); // Output: Hello from myFunction
```
**2. `Function` (uppercase):**
* Represents the function type itself.
* Used to declare variables, parameters, or return types that can hold any function, regardless of its specific signature (parameters and return type).
```dart
// Declaring a variable that can hold any function
Function myCallback;
// Assigning a function to the variable
myCallback = myFunction; // Assigning the 'myFunction' function
```
&nbsp;
Regex
```dart
import 'dart:core';
void main() {
final exp=RegExp(r'/(.+)\..+$');
print(exp.firstMatch('a/jk.mp')!.group(1)); // jk
print(exp.firstMatch('a/jk.mp')); // true
}
```

View file

@ -0,0 +1,160 @@
Basics
- hello world program
```dart
void main() {
print('hello world');
}
```
- data types
primitive:
int, float,double, char, string, bool
example
```dart
void main() {
String v = 'Rishav';
print(v);
}
```
dynamic : those who can contain any data type
var keyword
```dart
void main() {
var v = 'Rishav';
var v1 = 10;
var v2 = 80.12;
print(v);
print(v1);
print(v2);
}
```
dynamic keyword
unlike var whose datatype is fixed when assigned, in dynamic, datatype can be changed anytime
&nbsp;
const keyword : once value assigned, it cant be changed
&nbsp;
late keyword is non nullable and initialization will take place later and till then it wont recieve null and wait for its value.
```dart
import 'dart:io';
void main() {
const v = 'Rishav';
var v1;
v1 = stdin.readLineSync(); // input 12
dynamic v2 = 80.12;
v2 = stdin.readLineSync(); //input asd (a string)
print("Value of v is $v");
print(v1);
print(v2);
}
```
**Note** : In case of var and const , when we assign value, that value will be assigned during compile time so in future if that assign value (which maybe time or some value from api which can be changed) then in that case dynamic can be used to assign value at run time.
&nbsp;
final and const keyword are also similar but in case of objects(arrays) if const is used array is immutable too(means elements inside array cant be changed)
- comments
```dart
// inline comment
/*
*
* blocks of code
*/
/// documentation
```
- operators and other logical statements
if/else,switch,for , while , do-while loop and all operators even ternary are C like
&nbsp;
**Type casting**
```dart
void main() {
// string to integer
var one = int.parse('1');
assert(one == 1);
one += 10;
print('one: $one');
//integer to string
var oneString = 1.toString();
oneString += 'Rishav';
print('oneString: ' + oneString);
// decimal to string
var oneString2 = 3.1234.toString();
var oneString2D = 3.1234.toStringAsFixed(2);
assert(oneString2D == '3.12');
print('oneString2D: ' + oneString2D);
if (oneString2D == '3.12')
print('correct');
else {
print('incorrect');
}
}
```
&nbsp;
**Null aware operators**
Without null aware operator
```dart
class Num {
var num = 10;
}
void main() {
// var n = Num();
var n;
int no = 0;
if (n != null) {
no = n.num;
}
// print(n) // if var n = Num() then output : Instance of 'Num'
// print(no) if var n = Num() then output : 10
print(n); // output : null
print(no); // output : 0
}
```
With null aware operator
```dart
void main() {
// var n = Num();
var n;
int? no = 0;
// if (n != null) {
// no = n.num;
// }
no = n?.num;
// print(n) // if var n = Num() then output : Instance of 'Num'
// print(no) if var n = Num() then output : 10
print(n); // output : null
print(no); // output : null
}
```
In case of n being null if we dont want to assign null to `no` of n is null and instead some assign other v
`no = n?.num ?? 0;`
for directly assigning value to a variable whose value is null use `??=`
```dart
// ??=
void main() {
int? no;
print(no ??= 100); // outputs : 100
print(no); // outputs : 100
}
```

View file

@ -0,0 +1,9 @@
Commands
- there r two ways to execute code
`dart main.dart` : directly runs code. useful for quick and single dart file
`dart run main.dart` : useful for running a project with lot of other dependencies specified in `pubspec.yaml` file
- dart uses AOT(Ahead Of Time) compiler to create executable and jit(Just In Time) interpreter to run code directly which means features like hot reload can be used
`dart run main.dart` : jit interpreter
`dart compile exe main.dart -o output` and to run this self contained executable called output `./output`

View file

@ -0,0 +1,3 @@
- dart null check
use this `?.` for conditional thing and use `!.` for null check
`ModalRoute.of(context)!.settings.arguments;`