This section compares the two languages with Java to learn the Dart language syntax. First try the classic Hello World

void main() {
  print("Hello World");
}
Copy the code

variable

Note two things about variables:

  • Object,varwithdynamicThe use of
  • Distinguish betweenfinalwithconstTwo key words
Object, var, and Dynamic
  1. A variable is a reference, and uninitialized variables default tonull
  2. ObjectLike Java, it’s the parent of all classes,ObjectDeclared variables can be of any type
  3. varIs a variable modifierThe keywordWhen a declared variable is assigned a value, its type is determined and its value cannot be changed
  4. dynamicIs a variable modifierThe keyword. The actual type is not determined at compile time, but at run time.dynamicDeclared variable behavior andObjectThe same
  5. When declaring a variable, you can optionally add a specific type: int x = 20
  6. For local variables, as recommended by the current Dart code style, usevarmodified
void main() { Object i = 5; i = "Juice"; var j = "Juice"; // j=10; It is no longer allowed to change the value of j, it is determined to be a String, compiler error var k; // in this case, the compiler considers k as Object, so the following two operations are true: k = "Juice"; k = 100; dynamic z = "Juice"; // at runtime, dynamically determine what type z is z = 8; }Copy the code
Void test(a) {}Copy the code
Final differs from const
  1. finalIs a run-time constant. A final variable can only be set once
  2. constIs a compiler constant whose value is determined at compile time to make code run more efficiently
  3. The difference lies in:const A variable is a compile-time constant,finalVariables are initialized the first time they are used.
Void main() {// Final int I = 3; final j = 3; const k = 5; //const q=i; // Since I is a constant determined at runtime, we cannot assign to q but we can assign to k const q = k; }Copy the code
  1. The variables of the class can befinalBut it can’t beconst. ifconstA variable in a class needs to be defined asstatic constStatic constants (static as Java)