Dart Programming Interview Questions and Answers
Question - 51 : - How is whenCompleted() different from then() in Future?
Answer - 51 : -
- .whenComplete will fire a function either when the Future completes with an error or not, while .then returns a new Future which is completed with the result of the call to onValue (if this future completes with a value) or to onError (if this future completes with an error)
- .whenCompleted is the asynchronous equivalent of a "finally" block.
Question - 52 : - How to declare async function as a variable in Dart?
Answer - 52 : -
Async functions are normal functions with some sugar on top. The function variable type just needs to specify that it returns a Future:
class Example {
Future Function() asyncFuncVar;
Future asyncFunc() async => print('Do async stuff...');
Example() {
asyncFuncVar = asyncFunc;
asyncFuncVar().then((_) => print('Hello'));
}
}
void main() => Example();
Question - 53 : - What are Null-aware operators?
Answer - 53 : -
- Dart offers some handy operators for dealing with values that might be null.
- One is the ??= assignment operator, which assigns a value to a variable only if that variable is currently null:
int a; // The initial value of a is null.
a ??= 3;
print(a); // <-- Prints 3.
a ??= 5;
print(a); // <-- Still prints 3.
- Another null-aware operator is ??, which returns the expression on its left unless that expression’s value is null, in which case it evaluates and returns the expression on its right:
print(1 ?? 3); // <-- Prints 1.
print(null ?? 12); // <-- Prints 12.
Question - 54 : - Does Dart have syntax to declare interface?
Answer - 54 : - No, Class declarations are themselves interfaces in Dart.
Question - 55 : - What Is The Syntax To Handle An Exception?
Answer - 55 : -
The following syntax is used to handle an exceptions:
try {
// code that might throw an exception
}
on Exception1 {
// code for handling exception
}
catch Exception2 {
// code for handling exception
}
Question - 56 : - What Are Getters And Setters In Dart?
Answer - 56 : -
In Dart, Getters and Setters is also known as accessors and mutators. It allows the program to initialize and retrieve the values of class fields.
Question - 57 : - How To Create An Example Of This Keyword In Dart?
Answer - 57 : -
In Dart, the following code is used to create an example of this keyword.
void main() {
Car c1 = new Car('M2001');
}
class Car {
String engine;
Car(String engine) {
this.engine = engine;
print("The engine is : ");
}
}
Question - 58 : - What Is The Syntax To Declare Class?
Answer - 58 : -
The following is the syntax to declare class:
class class_name {
}
Question - 59 : - What Is The Use Of Truncate Methods?
Answer - 59 : -
Truncate method is used to return an integer after discarding any fractions digits.
Example:
void main() {
double n1 = 2.123;
var value = n1.truncate();
print("The truncated value of 2.123 = ");
}