22 May 2019
Dart
by Jerry Zhang
#Tip of the Day: “别认输,再加把劲,直到最后,超越自我; 不管相离多远,心都在一起,追逐着遥远的梦”
Classes and Objects
In Dart, when create an Object, the new
can be omitted.
Getters and setters are created by default, while final attributes only have getter methods.
No overloading in Dart.
Final attributes must be assigned a value when declared, either by assigning a value directly, or by constructor.
Accessibility is by library, which is a file in dart.
Underscore means private.
Getters and setters
Getters and setters methods for a special attribute can be written manually.
class Rectangle {
num left, top, width, height;
Rectangle(this.left, this.top, this.width, this.height);
// Define two calculated properties: right and bottom.
num get right => left + width;
set right(num value) => left = value - width;
num get bottom => top + height;
set bottom(num value) => top = value - height;
}
void main() {
var rect = Rectangle(3, 4, 20, 15);
assert(rect.left == 3);
rect.right = 12;
assert(rect.left == -8);
}
Constructor
The same as Java, but can be simplified.
class Person{
String name;
int age;
Person(this.name, this.age);
}
Constructors cannot be overloaded. If we need multiply constructors, use className.constructorName
Person(this.name, this.age, this.gender);
Person.withName(String name){
this.name = name;
}
Const constructor
All the attributes must be final. Use const in the constructor.
void main(){
const person = const Person("Tom", 20, "Male");
}
class Person{
final String name;
final int age;
final String gender;
const Person(this.name, this.age, this.gender);
}
factory constructor
class Logger {
final String name;
bool mute = false;
// _cache is library-private, thanks to
// the _ in front of its name.
static final Map<String, Logger> _cache = <String, Logger>{};
factory Logger(String name) {
if (_cache.containsKey(name)) {
return _cache[name];
} else {
final logger = Logger._internal(name);
_cache[name] = logger;
return logger;
}
}
Logger._internal(this.name);
void log(String msg) {
if (!mute) print(msg);
}
}
Type casting and testing
var person;
person = "";
(person as Person).work();
if (person is Person){
person.work();
}
“Call” methods
If a class implements the call method, then the objects of this class can be used as a method.
void main(){
var person = new Person();
person.name = "Tom";
person.age = 20;
person();
}
class Person{
String name;
int age;
void call(){
print("Name is $name,Age is $age");
}
}
Inheritance
Constructors are not inherited.
Child classes can overwrite the methods in parent classes.
Interface
Every class can be used as an interface.
Every attribute and method need to be overwritten.
We could use abstract class as an interface.
Mixins
Multiply inheritance.
class D extends A with B, C{
The method in the last class, c, will be used if there is a conflict.
Mixin classes cannot have explicit constructors, only default constructor.
Mixin can only inherit Object.
tags: Dart