21 May 2019
Dart
by Jerry Zhang
#Tip of the Day: “别认输,再加把劲,直到最后,超越自我; 不管相离多远,心都在一起,追逐着遥远的梦”
SDK
Use the stable version, otherwise there is some error in IntellijIDEA
Convention
Program entrance: main() method.
Naming convention: file name, use lowercase and underscore.
List and Map
List is similar as the array in JavaScript. And Map is like the array in PHP.
dynamic type
var or dynamic
~/ Divide, returning an integer result
int d = 20;
int e = 10;
print(d / e );
This will give us 2.0, which is a double.
However,
int d = 10;
int e = 3;
print(d ~/ e);
This will give us 3
We can include a variable inside a String with ${expression}
int aNumber = 5;
print('The number is $aNumber.');
result:
The number is 5.
Use “==” to compare Strings.
string.isEmpty will result a null pointer exception if this String is null.
Uninitialized variables have an initial value of null. Even variables with numeric types are initially null.
int lineCount;
assert(lineCount == null);
Important concepts
- Everything you can place in a variable is an object, and every object is an instance of a class.
- Dart is strongly typed. When you want to explicitly say that no type is expected, use the special type dynamic.
- Unlike Java, Dart doesn’t have the keywords public, protected, and private. If an identifier starts with an underscore (_), it’s private to its library.
??= Assignment operators; ?? if null
To assign only if the assigned-to variable is null, use the ??= operator.
// Assign value to b if b is null; otherwise, b stays the same b ??= value;
expression1 ?? expression2
String a;
String b = "Java";
String c = a ?? b;
print(c);
if a is null, then use b; otherwise use a.
For loop
var list = [1, 2, 3, 4, 5];
for (var i = 0; i < list.length; i++) {
print(list[i]);
}
for (var item in list) {
print(item);
}
Optional Parameters
void main(){
printPerson("A", age: 20);
}
printPerson(String name, {int age, String gender}){
print("name=$name,age=$age, gender=$gender");
}
If “[]” is used, then the parameter name like “age: “ can be omitted. It will be determined by positions.
void main(){
printPerson("B", 20);
}
printPerson(String name, [int age, String gender]){
print("name=$name,age=$age, gender=$gender");
}
Default parameter value
If a parameter’s value is not given, then use the default one.
printPerson(String name, [int age = 30, String gender = "male"]){
print("name=$name,age=$age, gender=$gender");
}
Function closure
void main(){
var func = a();
func();
func();
func();
func();
}
a(){
int count = 0;
printCount(){
print(count++);
}
return printCount;
}