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
,var
withdynamic
The use of- Distinguish between
final
withconst
Two key words
Object, var, and Dynamic
- A variable is a reference, and uninitialized variables default to
null
Object
Like Java, it’s the parent of all classes,Object
Declared variables can be of any typevar
Is a variable modifierThe keywordWhen a declared variable is assigned a value, its type is determined and its value cannot be changeddynamic
Is a variable modifierThe keyword. The actual type is not determined at compile time, but at run time.dynamic
Declared variable behavior andObject
The same- When declaring a variable, you can optionally add a specific type: int x = 20
- For local variables, as recommended by the current Dart code style, use
var
modified
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
final
Is a run-time constant. A final variable can only be set onceconst
Is a compiler constant whose value is determined at compile time to make code run more efficiently- The difference lies in:
const
A variable is a compile-time constant,final
Variables 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
- The variables of the class can be
final
But it can’t beconst
. ifconst
A variable in a class needs to be defined asstatic const
Static constants (static as Java)