Professional Documents
Culture Documents
Notes Lecture 9 Variable Declaration and Initialization & Null-Aware Operators
Notes Lecture 9 Variable Declaration and Initialization & Null-Aware Operators
&
Null -Aware Operators
The declaration means naming the variable and giving the proper data type to it, but dart being type
infer language, it can automatically know the data type. In contrast, initialization means
initializing the variable with some value of the appropriate data type.
Code:
void main() {
String s;
s = "Hello World";
print("s: $s");
Output:
s: Hello World
A Declaration of a variable must be made before it is used. We declare a variable using three
ways:
1. Using var keyword, since dart is a type infer language, it can automatically infer the type of
data we are assigning to it at first and make the variable of that data type.
Code:
void main() {
var s = "Erozgar";
// Printing the data type of 's' after assigning a value to it.
print(s.runtimeType);
Output:
String
Code:
void main() {
a = 100;
Output:
lib/main.dart:3:7:
a = 100;
^
Error: Compilation failed.
Code:
void main() {
int a = 100;
double b = 10.5;
print(s.runtimeType);
print(a.runtimeType);
print(b.runtimeType);
Output:
String
int
double
3. Using the dynamic keyword, we can change the value of the variable as well as its data type
also. Unlike in the case of var, we can't change its data type.
Code:
void main() {
// Creating a dynamic variable.
dynamic a = "Erozgar";
print(a.runtimeType);
a = 100;
print(a.runtimeType);
Output:
String
int
Null-Aware Operators
Null-aware operators in dart allow you to make computations based on whether or not a
value is null. It’s shorthand for longer expressions. A null-aware operator is a nice tool
for making nullable types usable in Dart instead of throwing an error. These operators
are used in fullback in combination that you will get value at the end but not null.
Null-aware operators are used in almost every programming language to check whether
the given variable value is Null. The keyword for Null in the programming language Dart
is null. Null means a variable which has no values assign ever and the variable is
initialized with nothing like.
1. Default Operator: ??
We use ?? when you want to evaluate and return an expression if another expression
resolves to null.
The null-aware operator is ??, which returns the expression on its left unless that
expression’s value is null. In which case it’s null it returns the expression on its right:
Placing … before an expression, inserts a list into another only if it’s not null.
It helps add multiple values to our collection like List, Map, and Set.