Variables

Jun's Coding Journey·2023년 8월 9일
0

[Learn] Dart

목록 보기
3/6

Hello World


Every Dart code can only be run with the main function. Without the main keyword, the function will not run.

When ending a code statement, Dart needs to have a semi-colon.

void main() {
  print('hello world'); // hello world
}

 

The Var Keyword


Use the var keyword to store data within variables.

Without specifying the type of a variable, the Dart compiler will automatically know the type.

void main() {
  var name = 'John';
}

 
We can either use the var keyword or explicitly specify the type when declaring a variable.

void main() {
  var name = 'John';
}
void main() {
  String name = 'John';
}

 
We can only modify the same type of data within a variable.

void main() {
  // valid
  var name = 'John';
  name = 'Dave'
}
void main() {
  // invalid
  var name = 'John';
  name = 12;
}

 
The convention is to use the var keyword when declaring local variables and the explicit type notations for classes.


 

Dynamic Type


The dynamic keyword allows variables to be of any type. Dynamic is used when the type of the value is unknown.

void main() {
  dynamic name;
  name = 'John';
  name = 12;
  name = true;
}

 
To use methods with dynamic variables, we need to check the type.

void main() {
  dynamic name;
  if (name is String) {
    name.length;
  }
  if (name is int) {
    name.isEven;
  }
}

 

Nullable Variables


Null safety helps developers to not reference null values and avoid runtime errors.

It is important to specifically describe if a variable is null.

By default, all variables are non-nullable (should never be null).

void main() {
  String? name = 'John'; // this MIGHT be either 'John' or null
  if (name != null) {
  	name.isNotEmpty;
  }
}
void main() {
  String? name = 'John'; // this MIGHT be either 'John' or null
  name?.isNotEmpty
}

 

Final Variables


The final keyword can be used to declare variables that cannot be modified.

The is similar to the const keyword in JavaScript.

void main() {
  final name = 'John'; // this variable cannot be modified
}

 

Late Variables


The late keyword comes before either the var or the final keyword to specify a value much later (not directly).

Until the value is specified, the variable cannot be used.

For example, This can be useful when trying to fetch data from an outside API.

void main() {
  late final name; // this variable will be filled LATER
  name = 'John';
  print(name);
}

 

Constant Variables


The const keyword creates a compile-time constant. This means that the variable is known ahead of compilation and will never change.

void main() {
  const max_allowed_price = 120;
}

profile
Greatness From Small Beginnings

0개의 댓글