- Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
1. Classes and objects
In Flutter, a class is declared using the class keyword and an Object is generated using new plus the constructor. All objects inherit the Object class by default. Dart generates getter and setter methods by default. Properties and methods are accessed through point syntax. Dart methods do not support overloading. A final modified property must define an initial value.
Declare a class:
class LGPerson { String? name; int? age; final String hobby = 'coding'; void run() { print("name:$name age:$age"); }}Copy the code
Declare an object and method call:
LGPerson p = LGPerson();
p.name = 'LS';
p.age = 18;
p.run();
Copy the code
In Dart, the same file is not privatized; only in different files can you have private attributes. Create a new file and add a new LGTeacher class that exposes only the height property and printTeacher method.
class LGTeacher { String? _name; int? _age; int? height; void _run() { print("name:$_name age:$_age"); } void printTeacher() { _run(); }}Copy the code
As you can see, private properties and methods are not externally accessible, but are still accessible if the class is in the same file.
2. Constructor
Once a class is defined, it has a constructor by default. Is equivalent to:
LGperson(){}
Copy the code
You can customize the constructor, and if you do, the default constructor is invalid.
LGPerson(int age,String name){
_name = name;
_age = age;
}
LGPerson p = LGPerson(18,"test");
Copy the code
If this is not a private property, the property and parameter names will be the same:
name = name;
age = age;
Copy the code
You can rename the parameter or prefix the attribute with this., but the Dart syntax sugar is recommended for automatic assignment.
LGPerson(this.age,this.name);
Copy the code
Attributes do not need to be Nullability after using this syntactic sugar.
class LGPerson { String name; int age; LGPerson(this.age,this.name); void run() { print("name:$name age:$age"); }}Copy the code
If the property is final, the property cannot be changed afterwards.
You can also create named constructors in class:
LGPerson.withName(this.name,this.age); // call LGPerson p2 = lgPerson. withName("kk", 18);Copy the code
What’s the point of final? Well, there’s one application here, which is constant objects. When all properties of a class are final and constructors const, the resulting object is a constant object. We need all properties to be final, otherwise the constructor will fail to be const.
class LGPerson { final String name; final int age; final int height; const LGPerson(this.age,this.name,this.height); // LGPerson.withName(this.name,this.age); void run() { print("name:$name age:$age"); }}Copy the code