- B - Binary function
- A function that accepts two parameters and returns a single result
- to repeatedly combine the elements of the iterable.
- reduce()
- fold()
- C - Comments
- /// for the documentation or multiple line. When press enter next line will be comments and VS Cose generate ///
- // for single line comment.
- C - Constant
- Can const be null? if null can
const
change later? - C - Class
- Every class is a subclass of the object class.
- this keyword
- It’s used to differentiate between instance variables and parameters with the same name. It refers current instance of the class.
- class Person3 {Person3();}
- Person and person1 are the same class
- class Person {final String name;final int age;Person({required String name1, required int age1}): this.name = name1,age = age1;}class Person1 {final String name;final int age;Person1({required this.name, required this.age});}
- Getter: Person and person1 are the same class
- class Person {final String firstName;final String lastName;final String fullName;const Person({required this.firstName,required this.lastName,}) : fullName = '$firstName $lastName';}class Person1 {final String firstName;final String lastName;String get fullName => '$firstName $lastName'; // getterconst Person1({required this.firstName,required this.lastName,});}
- Named Constructor
- const Person.new1() : name = "galib", age = 20;
- const new1 = Person.new1();
- const Person.new2({required this.name}) : age = 30;
- const new2 = Person.new2(name: 'Galib');
- _myVariable - An underscore (_) at the beginning indicates that it is a private variable.
- Properties of the Object.
- runtimeType - Check the type of the instance of the object/variable during runtime (not compile time).
- Why and how can I use the toSting() method.
- Because your class is a subclass of the Object class (Super Class).
- What is method?
- Functions inside the class define the behavior of the object.
- What is the meaning of the annotation @override?
- This does not overwrite. This re-implements the superclass method at compile time.
- Use when
- Overriding a method from a parent class.
- Implementing a method defined in an interface.
- Why @override is not needed in an extension?
- What is singleton class?
- One instance and provides a global point of access to that instance.
- In Dart three layer deep.
- print() and toString() relation.
- In Dart, the toString() method is automatically (implicit) called during print(). In addition, toString() is also a method of the Object superclass.
- How can a property have both a getter and a setter behavior?
void main() { var myCar = Car(); print(myCar.speed); // Getter myCar.speed = 20; // Setter print(myCar.speed); } class Car { int speed = 0; // Property If
final int speed = 0
, can't be set either. }- This property has no control. If
final int speed = 0
, then it can't be set either. So, this type of setter does not work properly, so a setter function is required. - However, this myCar.speed = 20; does not affect any other instance. But we can do this by using static.
- Why use static?
- Static getters can be accessed without creating an instance of the class.
- Setter
- void main() {final p = Person();try {p.waking(speed: -10);} catch (e) {print(e);}}class Person {int _speedPrivate = 0;int get speedGet => _speedPrivate;set speedSetter(int newSpeed) {if (newSpeed < 0) {throw Exception('Speed cannot be negative.');}_speedPrivate = newSpeed;}void waking({required int speed,}) {this.speedSetter = speed;print('This persons speed is $speed k/h');}void stop() {speedSetter = 0;print('Stopped.');}}
- When you write
this.speedSetter = speed;
, it translates into calling the setter method and passingspeed
as the argument fornewSpeed
. Dart does this automatically, so you don’t need to include parentheses when using a setter. It is just syntactic sugar to make it look like you're assigning a value directly. - A value to a setter directly with the assignment syntax (
=
), not by calling it like a regular method (()
). - Setters can only accept one argument.
- Getter
- Constructor tips
- A constructor is a special function that does not have a return type, not even void.
- It can be overloaded by using different parameters, allowing for multiple ways to create an instance of a class.
- This function may have a body.
- Constructors are not inherited by default. So when you create a subclass, you need to explicitly define its superclass constructor.
- class Mom extends Person {const Mom() : super(role: Role.mom);}
- Super class constructor must call it form the subclass using super keyword.
- class Mom extends Person { const Mom({required super.role});}
- By using
super.role
, theMom
constructor passes therole
parameter directly to thePerson
constructor. - Factory Constructor | Class clustering
- Factory constructors are special methods that allow you to return (create) an instance of a (this) class (or this subclass) without being required to return a value in the same way a typical function does.
- factory Vehicle.truck() => Truck();
- print(Vehicle.truck()); // It creates subclass Truck instance;
- Even if it could return a
void
, the factory constructor's purpose is to return an instance ofVehicle
. - Return an existing instance rather than creating a new one each time.
- Why mixin is used?
- Directly, multiple inheritance is not supported in Dart. Therefore, hierarchical inheritance is possible (not a good idea), but a class cannot inherit from more than one class at the same time. Dart uses a mixin-based approach to achieve similar functionality.
- ... (Spread Operator) VS .. (Casade Notation)
- Why use const before a constructor?
- Wha is efficient lookup, lookup table and hash table?
- Dart can't create a range. How can we solve this issue?
- We have to bild custom rang function.
- Why you need to learn generics?
- final double doubleValue = getDoubleValue();
- Call site accept the double value;
- For user readability, the generic name can be either E (Element) or T (Generic Type).
- bool typesMatch<L, R>(L a, R b) { return a.runtimeType == b.runtimeType; //L==R; }
- a and b are the actual objects you pass into the function. These objects must be instances of types that L and R represent.
- The objects
a
andb
could be any objects that are of typesL
andR
, respectively, and these types could be extended fromObject
(which all Dart classes inherently do). - L and R are generic type parameters.
- What is the difference between errors and exception?
- Error
- Errors are not meant to be caught
- Never try an error (catch).
- Predefined (documented) and system crashes.
- Exception
- Exception are meant to be caught.
- Keyword try, catch and throw.
- An exception is a class and a condition where the program can recover. You throw an instance of an exception using throw keyword.
- What is typedef?
- For
typedef
, function signatures are mainly used as function parameters. - What is StreamController?
- Just an object creating a stream with the add, addError, or close functionality.
- Dart promotional conversion?
- T operator +(T? other) { final thisShadow = this; if (thisShadow != null && other != null) { return thisShadow + other as T; } why final thisShadow = this; is use?
The Future
keyword adds functionality to a function by enabling asynchronous operations. It allows the function to return aFuture
datatype, making it more efficient for handling asynchronous tasks.
void main() async {await ab();print(await cd());print(await xy());}Future<void> ab() async => print('Galib');//we don't need async keywordFuture<String> cd() => Future<String>.delayed(Duration(seconds: 2),() => 'Iftekhar Galib',);Future<int> xy() {const x = 10;const y = 20;const z = x + y;return Future.value(z);}
Future chaining with then().
is - Type of the datatype | Check variable at runtime
print(age is! int); --> true or false.
late final String description; //Can't assign a second time.
- Avoid using late randomly inside try-catch blocks, as it can lead to late initialization errors and make your code harder to reason about.
- Why Using late in Constructors Can Be Risky?
- Because constructor runs at the compile time and creates LateInitializationError error and increased complexity.
- Late variable should not be initialized inside the constructor, the late variable won't be lazy.
For specific problems
- L-Loops
- for Modern format - for(String name in names)...
- continue Format - for (String name in names) { if (name.startsWith('M')) {print(name); continue; print(name);} print(name); } // The first print statement inside the if-else block is executed. In Dart, the
continue
statement is used to skip the current iteration of the loop and proceed with the next one if available. - break format - // The
break
statement completely exits the loop. - While Loops - const names = ['A', 'S', 'M', 'I', 'R']; var counter = 0; while (counter < names.length - 1) { ++counter; // Increment before accessing the list print(names[counter]); // This skips the first element } } // Must after printing, counter is incremented, and the loop proceeds to the next element.
- So, ++counter or count++ shows the same results but what happen when using print(names[++counter]);
- wow, var counter = -1; while (++counter < names.length - 1) {
- myFunction() {} what is the default return type?
- dynamic. Not the void; here by default dynamic and return by default the null. So, if you don't want to return null then, use void. Finally void can't invoke the function and assign the result to a variable. And dynamic can return null and assign the result to a variable.
- Name parameter
- {} is used for named parameter.
- Must have a null safety operator or a default value. getData(); returns null because the null safety operator is used. If the use default value in a named parament then can't assign null as a parameter. By default, name parameter can't be null.
- Null safety only applicable to named parameter.
- You don't need to follow the parameter order.
- void main() {myFunc();myFunc(name:null);myFunc(name: 'constant');}void myFunc({String? name = 'Word'}) {print('Hello, $name');}
- What will be the output? Just comment it. If I remove the null safety operator, what will happen?
- Required/mandatory named parameter
- You always have to send a parameter with a name.
- void myFunc({required int? name}) {// Accept a null value but default value is not accepted.
- Positional Parameter
- Passed in Order, no names associated with it, always required but no keyword and no default values.
- If null accepted(?), then must assign null argument.
- Optional Positional Parameter ([ ])
- Basic format: void myFunction([ String? name, String lastName = 'Bar', ]) {
- Mixing Various Parameter Styles
- void myFunc( String? firstname, [ String? lastName = 'Galib',]) {
- void myFunc( String? firstname, {String? lastName = 'Galib',}) {
- Function as a parameter
- Yes, a function is a datatype. Oh, any data types can be passed to another function.
- Predicate?
- Is a function return true or false.
- ? (Null-aware Operator) Vs ! (Null Assertion Operator) Vs ??
- Null-aware Operator(?) - Safely access a property or method of an object that might be null, without throwing an error if it is null.
- String? name; int? length = name?.length; // length will be null if name is null
- Null Assertion Operator(!) - A value must not be null; otherwise, it will throw a NoSuchMethodError.
- String? name; if (name != null) { print(name!); } // Commonly used when you have checked for null
- How is the datatype modifier determined by Dart?
- Like final a = 10/5; // it would be double
- like final a = 10*5; It would be int;
- Flip operator
- Boolean Flip
- myValue = !myValue;
- Bitwise Flip
- var flipped = ~num;
- Flipping an Iterable or List
- Flipping Key-Value Pairs in a Map
- State Management
- Provider, Riverpod, and Bloc
- Bloc is complex but separate business form UI. Good for async and well-structured for larger applications with complex state management.
- Stream
- asyncExpand
- stream.map
- Stream<String> get capitalized => transform( ToUpperCase(), );
- Stream<String> names = Stream.fromIterable( [ 'elements', 'aa', 'cccc', ], );
- class StreamErrorAbs<T> extends StreamTransformerBase<T, T> { @override Stream<T> bind(Stream<T> stream) { final controller = StreamController<T>(); stream.listen( controller.sink.add, onError: (_) {}, onDone: controller.close, ); return controller.stream; } }
- Stream<T> absreError2() => transform( StreamTransformer.fromHandlers( handleError: (a, b, sink) { print('a .$a'); print('b => $b'); //sink.close(); }, ), );
- Stream<T> absroError1() => handleError( (_, __) { print('ddd'); }, );
- asyncMap()
- asyncExpand()
- Most of the time, mobile apps don’t need a Save button.
- Conversion | int a = 10; double b =20.01;
- Not possible a = b;
- But a=b.toInt();
- Dwon casting | Casting
- num a = 10; // Now variable a is a int type
- int x = a; // Not accepted because down casting accepted.
- int b = a as int; // Accepted because it's a down casting
- double c = a as double; // Type 'int' is not a subtype of type 'double' in type cast
- double c = a as int; // Sibling casting not accepted
The variables can involve different modifies const, final var or dynamic. These keywords control the behaviors of the variables in terms of mutability, type safety and initialization. var is the default modifier.
- Can a const value be assigned to a final variable?
- Yes, you can assign a const value to a final variable.
- const age = 25; final ageYear = age; // Valild
- It is assigned once, but it's a constant value of type int at runtime.
- Can a const value be assigned to a final variable?
- No, you can assign a final value to a const variable.
- final age = 25; const ageYear = age; // Invalild
- Can a const value be assigned to a const variable?
- Yes, you can assign a const value to a const variable.
- const age = 25; const ageYear = age; // Valild
- What is type promotion?
- Less precision
- final a = 10;
- More precision (type promotion)
- final int a = 10;
C - Constant
- Can const be null? If null is accepted, can
const
change later?
- Yes, const can be null only if type is nullable. No, const values are immutable and cannot be changed once set, regardless of whether the value is null or not. The value of a const variable must be known at compile time, and once set, it cannot be modified. Can't change internally or assign a new value (can share). const int? a = null; // 'a' is a compile-time constant and nullable
- const don't allow mutability.
- const don't allow mutability
- const constAge = 10; final finalAge = 20; constAge = finalAge; //Not allowed.
- const a =10; const b =a; // Allowed.
- Dynamic
- Can change datatype.
- F -Final
- Can't assign a new value but can change(mutation) internally (can't share). It is a runtime constant.
- final Allows Mutation of Variable Contents
- const constAge = 10; final finalAge = 20; finalAge = constAge; // allowed
- It's basically constant so
- final a = 50; a=10;//Not allowed.
- V- Var
- Initially, the datatype of a variable declared with
var
is implicitly determined at compile time in Dart. - The assigned value can be changed at runtime, and it can also be modified internally.
- var is the default modifier.
- Inferred means automatically deduced or figured out by the system.
- If you don't assignee var then its totally acts like dynamic
- What is WidgetBuilder?
- It is a function that accepts context(BuildContext) as a parameter and returns dynamic widget(s).
- BuildContext Vs WidgetBuilder Vs ItemBuilder Vs Builder [Dynamic nature]
- BilderContext - Can allow access to other widgets and properties of the tree. It also holds the location of a widget | object.
- WidgetBuilder - Create a new widget (single) based on the BuilderContext | function.
- typedef WidgetBuilder = Widget Function(BuildContext context);
- ItemBuilder- Create a new list of widgets (ListView, GridView where each item is intexed) based on the BuilderContext location representations | function.
- typedef ItemBuilder = Widget Function(BuildContext context, int index);
- Builder - Create a new child [widget] using the WidgetBuilder function based on the BuildContext parameter | widget.
- What is FutureBuilder?
- StreamBuilder
- Data cannot be held even when an interruption occurs. StreamBuilder retains data during interruptions.
No comments:
Post a Comment