Variables

Cards (9)

  • Dart has two kinds of variables: local variables and instance variables (also called fields).
  • Uninitialized variables that have a nullable type have an initial value of null. Even variables with numeric types are initially null, because numbers—like everything else in Dart—are objects.
  • Production code ignores the assert() call. During development, on the other hand, assert(condition) throws an exception if condition is false.
  • You don’t have to initialize a local variable where it’s declared, but you do need to assign it a value before it’s used.
  • The late modifier has two use cases:
    • Declaring a non-nullable variable that’s initialized after its declaration.
    • Lazily initializing a variable.
  • When you mark a variable as late but initialize it at its declaration, then the initializer runs the first time the variable is used.
  • If you never intend to change a variable, use final or const, either instead of var or in addition to a type. A final variable can be set only once; a const variable is a compile-time constant.
  • You can also use const to create constant values, as well as to declare constructors that create constant values. Any variable can have a constant value.
  • In contexts where an expression must be constant, the const keyword is implicit, doesn’t need to be written, and shouldn’t. Basically, any place where it would be an error to write new instead of const, Dart allows you to omit the const.