11 KiB
11 KiB
Dart
- Dart is the language behind flutter
- Dart is an object oriented language
- can run on Android,ios,desktop and web
Variable Delecartion and Initialization
- store values and reference them multiple times
- Variable name should start with small letter.
- Variable name should be declared in camelCase.
- Combination of lowercase and uppercase letter, as well as all digits from 0 to 9 and the underscore character like this
- first character cannot be a digit
String Concatenation and Interpolation
To concatenate two string use "+" sign .
Can also use "$" sign inside the string.
e.g print("My name is $firstName $lastname")
Interpolation can evaluate an expression inside a string with the ${} syntax.
e.g print('Sum is ${num1 + num2})
String Escaping
Write the backslash before the single quote inside the string.
e.g print('Today I\'m feel good')
Can solve with double quote too.
e.g print("Today I'm feel good")
You can make a "raw" string by prefixing it with r
e.g print(r'C:\Window\System 32')
Multiline String
Use a triple quote (''' or """), with either single quote or double quote at the beginning and at the end.
e.g print( '''
the initial newline is ignored
but the last newline is not ignored
''');
Ternary Operator
The conditional operator is considered as short hand for if-else statement. Conditional operator is also called as “Ternary Operator”.
result = testCondition ? trueValue : falseValue
Type inference with "var"
We don't need to declare variable type explicitly,can use "var" instead.
Can be set more than once.
The final keyword
The final keyword is used to hardcode the values of the variable and it cannot be altered in future, neither any kind of operations performed on these variables can alter its value (state).
-final means read only (can only be set once)
-If we try to reassign the same variable then it will display error.
e.g void main() {
final geek1 = "Geeks For Geeks";
print(geek1);
// Can't reassign like this
geek1 = "Geeks For Geeks Again!!"; /
// Assigning value to geek2
// variable with datatype
final String geek2 = "Geeks For Geeks Again!!";
// Printing variable geek2
print(geek2);
}
The Const Keyword
The const keyword in Dart behaves exactly like the final keyword. The only difference between final and const is that the const makes the variable constant from compile-time only. Using const on an object, makes the object’s entire deep state strictly fixed at compile-time and that the object with this state will be considered frozen and completely immutable.
Using var,final,const with lists
-You can declare list variables as var,final,const.
-Final and Const variables can only be set once.
-Final variables can't be re-assigned but you can still modify their contents.
-But not with const variable.
Sets and List
-Sets are collection of unique values using curly brackets.
-Lists can contain duplicate values using square brackets.
-Sets can use union method, intersection and difference method.
Map
-Used to store a collection of key value pairs.
-When declaring a Map with var/final/const, key and values can have any type we want.
-You can add type annotations to lists, sets and maps literals.Type annotations are not required but they help you wirte safer code.
e.g Map <String, dynamic> person ={
'name' : 'Lilly',
'age' : 20,
};
As Operator
If you declare a map with dynamic values and want to assign map values to variables of specific type,you can use the 'as' operator.
e.g Map <String, dynamic> person ={
'name' : 'Lilly',
'age' : 20,
};
var name = person ['name'] as String;
print(name);
Spreads
"..." adds the elements of a list to the enclosing list/collection.
e.g final colors =[
'green','gret',
...['black','cyan'],
];
The assertion operator(!)
-assign nullable value to non-nullable value.
-IF we're sure that a nullable variable will always have a non-nullable value,we can use the assertion operator(!).
-'!' is also called the bang operator.
e.g void main(){
int x = 7;
//To indicate that a variable might have the value null, just add ?
int ? maybeValue;
if (x > 0){
maybeValue =x;
}
// valid, value is non-nullable
int value = maybeValue !;
print(value);
}
Functions
-encapsulate some code and reuse it multiple times
eg:
void main(){
sayHi();
}
void sayHi(){
print('Hi');
print('Welcome');
}
Required and default values
1.Without null safety : arguments can be omitted.
2.With null safety:
-make arguments nullable (e.g {String ? name})
-make arguments non-nullable
use a default value ( e.g {String name = 'Andera'})
mark them as required ( e.g {required String name})
3.Null safety gives you compile-time guarantees about what can and cannot be null.
Fat arrow notation(=>)
Need a function body with only one statement?Use the "=>" notation.
eg: int sum (int x,int y)=>x + y;
The where and firstWhere methods
where :filter items inside a collection
firstWhere :find an item inside a collection
eg:
void main(){
cost list =[1,2,3,4];
final even =list.where((value)=>value % 2 == 0);
final value =list.firstWhere((x)=>x == 4,orElse:()=> -1);
}
The reduce method
-Used to combine all items inside a list and produce a single result.
eg:
void main(){
cost list =[1,2,3,4];
final sum =list.reduce((previousValue,element)=>previousValue + element);
}
Const constructors
Have a class where all variables are final?User a 'const' constructor.
eg:
class Complex{
const Complex(this.re,this.im);
final double re;
final double im;
}
Static methods and variables
-The static variables belong to the class instead of a specific instance. A static variable is common to all instances of a class: this means only a single copy of the static variable is shared among all the instances of a class. The memory allocation for static variables happens only once in the class area at the time of class loading.
-Use static const to define a global constant that belonds to a class.
-Static variables can be declared using the static keyword followed by data type then the variable name
e.g static [date_type] [variable_name];
-The static variable can be accessed directly from the class name itself rather than creating an instance of it.
e.g Classname.staticVariable;
Private variables and methods
-Encapsulate things that should not be accessible outside a class.
-You cannot directly access a private name from a different library
-Private identifier in Dart start with an underscore. ( e.g _balance, _ 123)
Abstract classes
-connot be instantiated
-to define an interface that can be implemented by subclasses
-You can always assign an instance of a subclass to a variable of the parent class
eg:
abstract class Shape{
double get area;
}
class Square extends Shape{
Square(this.side);
final double side;
@override
double get area=>side * side;
}
void main(){
// final shape =Shape();
final square =Square(10);
}
Difference between implements and extends
keyword type abstract methods concrete method
-extends single must override can override
-implements multiple must override must override
Copying objects with copyWith
If yout need copy-behaviour in your immutable classes,create a 'copyWith' method.
eg:
class Credentials {
final String email;
final String password;
const Credentials({this.email = '', this.password = ''});
Credentials copyWith({
String? email,
String? password,
}) {
return Credentials(
email: email ?? this.email,
password: password ?? this.password,
);
}
@override
String toString() => 'Credentials($email,$password)';
}
void main() {
const credentials = Credentials();
final update = credentials.copyWith(email: "example@gamil.com");
print(update);
}
Mixins
-to share functionality in multiple classes without code duplication
-Mixins can't be instantiated
eg:
mixin Swimming {
void swim() => print('swimming');
}
class Animal {
void breathe() => print('breathing');
}
class Fish extends Animal with Swimming {}
class Human extends Animal with Swimming {}
void main() {
final fish = Fish();
fish.swim();
final human = Human();
human.swim();
}
Extensions
-add functionality to existing classes,without modifying them.
-only named extensions can be imported
eg:
extensins.dart
import number_parsing.dart;
void main(){
int.tryParse('123');
'123'.toIntOrNull();
'456'.toIntOrNull();
}
number_parsing.dart
extension numberParsing on String{
int? toIntOrNull()=>int.tryParse(this);
}
Asynchronous
Asynchronous operation let your program complete work while waiting for another operation to finish.
-Fetching data from network
-Writing to a database
-Reading data from file
Future
- A future represents the result of an asynchronous operation, and can have two states: uncompleted or completed.
-A future can't listen to a variable change.
-It's a one-time response.
Async and await
Async
- You can use the async keyword before a function’s body to mark it as asynchronous.
Await
-You can use the await keyword to get the completed result of an asynchronous expression. The await keyword only works within an async function.
-Await is only allowed inside async functions
-To wait until a future completes
Future<String> createOrderMessage() async {
var order = await fetchUserOrder();
return 'Your order is: $order';
}
Future<String> fetchUserOrder() =>
// Imagine that this function is
// more complex and slow.
Future.delayed(
Duration(seconds: 2),
() => 'Large Latte',
);
Future<void> main() async {
print('Fetching user order...');
print(await createOrderMessage());
}
Stream
-Streams provide an asynchronous sequence of data.
-There are two kinds of streams: single subscription or broadcast.
Future<int> sumStream(Stream<int> stream) async {
var sum = 0;
await for (var value in stream) {
sum += value;
}
return sum;
}
Stream<int> countStream(int to) async* {
for (int i = 1; i <= to; i++) {
yield i;
}
}
Future<void> main() async {
var stream = countStream(10);
var sum = await sumStream(stream);
print(sum); // 55
}