3 KiB
3 KiB
Basics 2
for-in loop and foreach loop : used with collections
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
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>
}
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
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;
More about Lists
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"] ));
}