variable

The VAR can infer its own type

main(List<String> args) {
  var name = 'Bob';
  
  var a = 1, b = 2, c = 3;
  var d, e, f;
  print("a=${a} b=${b} d=${d} e=${e} f=${f}"); //a=1 b=2 d=null e=null f=null

  d = true; e ="123"; f =123;
  print("a=$a b=$b d=$d e=$e f=$f"); //a=1 b=2 d=true e=123 f=123
}
Copy the code

Variables only store references to objects. Here the variable named name stores a reference to a String object, and “Bob” is the value of that object.

The name variable is inferred to be of type String, but you can specify a type for it. If an Object reference is not limited to a single type, it can be specified as an Object (or dynamic) type.

dynamic name = 'Bob';
Copy the code

Another way is to explicitly declare the types that can be inferred:

String name = 'Bob';
Copy the code

The default value

In Dart, variables of uninitialized and nullable types have a default initial value of NULL. (If you have not migrated to null-safe, all variables are nullable types.) This is true even for numbers, because everything is an object in Dart, and numbers are no exception.

int? lineCount;
assert(lineCount == null);
Copy the code

Calls to assert() will be ignored in production code. During development, assert(condition) will throw an exception if the condition is judged to be false. See Assert for details.

  1. If null security is enabled, non-null variables must be initialized before they are used:
int lineCount = 0;
Copy the code

You don’t have to initialize it where you declare a local variable, but you do need to assign it a value before you use it. Here’s an example, because Dart can detect that lineCount is non-empty when passed to print()

void main(){
    int lineCount;
    lineCount = 0;
    print(lineCount);
}
Copy the code

The late keyword implements delayed initialization

Dart 2.12 adds the lazy loading modifier, which has two use cases:

  • Declare a non-null variable and initialize it after declaration.
  • Delay initialization of variables.

Dart’s control flow analysis can usually detect if a non-null variable is set to a non-null value before using it, but sometimes the analysis fails. Two common cases are top-level variables and instance variables :Dart is usually not sure if they are set, so it doesn’t try. If you are sure that a variable was set before it was used, but Dart disagrees, you can resolve the error by marking the variable late:

late String description;

void main() {
  description = 'Feijoada! ';
  print(description);
}
Copy the code

If late fails to delay the initialization of a variable, a runtime error occurs when using the variable. \

If you mark a variable as late but initialize it at declaration time, the initializer will run when the variable is first used. This lazy initialization is handy in several cases:

  • This variable may not be needed, and it is expensive to initialize.
  • You’re initializing an instance variable, and its initialization requires access to this.

In the following example, the _readThermometer() function won’t be called if you’ve never used temperature before:

// This is the program's only call to _readThermometer().
late String temperature = _readThermometer(); // Lazily initialized.
Copy the code

Final and Const

If you don’t want to change a variable, you can decorate it with the keyword final or const, which can replace the var keyword or precede a specific type. A final variable can be assigned only once; A const variable is a compile-time constant (const variables are also final). A top-level final variable or a class’s final variable is initialized the first time it is used.

Although a final object cannot be modified, its fields can be modified. By contrast, const objects and their fields are immutable: they are immutable.

The instance variablesCan befinalBut it can’t beconst

In the following example we create and set two final variables:

final name = 'Bob'; // No type comment
final String nickname = 'Bobby';
Copy the code

You cannot change the value of the final variable:

name = 'Alice'; // Error: The final variable can only be set once.
Copy the code

The keyword const decorates a variable to indicate that it is a compile-time constant. If you use const to modify a variable in a class, you must add the static keyword, that is, static const. A const variable can be assigned directly when declared, or it can be assigned using another const variable:

const bar = 1000000; // Unit of pressure (dynes/cm2)
const double atm = 1.01325 * bar; // Standard atmosphere
Copy the code

The const keyword can be used not only to define constants, but also to create constant values that can be assigned to any variable. You can also declare constructors to be const. Constructors of this type create objects that are immutable.

var foo = const [];
final bar = const [];
const baz = []; // Equivalent to `const []`
Copy the code

We can omit the const keyword if we assign a constant using an initialization expression, such as baz above, which omits const. See don’t use const for redundancy.

The value of variables that are not decorated with final or const can be changed, even if they have previously referenced const values.

foo = [1.2.3]; // Was const []
Copy the code

The value of a constant cannot be modified:

baz = [42]; // Error: Constant variables cannot be assigned.
Copy the code

You can use type checking and casts (is and AS) in constants, if in collections, and expansion operators (… And… ?). :

const Object i = 3; // Where i is a const Object with an int value...
const list = [i as int]; // Use a typecast.
const map = {if (i is int) i: 'int'}; // Use is and collection if.
const set = {if (list is List<int>) ...list}; / /... and a spread.
Copy the code