Classes and objects
- Declare a class using the keyword class
class Person{
}
Copy the code
- Create an object with the keyword new, which can be omitted
void main() {
var p1 = new Person();
var p2 = Person();
}
Copy the code
- All objects inherit from the Object class
Properties and Methods
- Property generates getter and setter methods by default
void main() { var p = new Person(); P.name = "huang Jiaju "; p.age = 31; print("name = ${p.name}, age = ${p.age}"); } class Person{ String name; int age; }Copy the code
Print result:
Name = Huang Jiaju, age = 31Copy the code
You can see that the properties name and age can be reassigned and retrieved, that is, setter and getter methods are generated by default
- Properties declared with final only have getter methods
void main() { var p = new Person(); // p.gender = "Female"; 'gender' can't be used as a setter because it's final print("gender = ${p.gender}"); } class Person{ String name; int age; final String gender = "Male"; }Copy the code
If the gender property is declared with the final keyword, it has only getter methods and cannot be reassigned
-
Properties and methods pass. access
-
Methods cannot be overloaded
class Person{ String name; int age; final String gender = "Male"; Void work(){} // void work(int speed){// //} The name 'work' is already defined.Copy the code
Dart does not support method overloading, even if the method has a different parameter, as long as the method name is defined.
Visibility of classes and members
- Visibility in Dart is measured in libraries
- By default, each Dart file is a library
- Use _ to indicate library privacy
- Import the library using import
Write the Person class separately in the Person.dart file
class Person{
String name;
int age;
final String gender = "Male";
void work(){
}
}
Copy the code
To call the Person class in another Dart file, import Person.dart using import
import 'Person.dart';
void main() {
var p = new Person();
}
Copy the code
When you add _ to the Person class name, the class cannot be called by other files
class _Person{
String name;
int age;
final String gender = "Male";
void work(){
}
}
Copy the code
When an attribute is preceded by an _, the attribute cannot be called directly
class Person{
String _name;
int age;
final String gender = "Male";
void work(){
}
}
Copy the code
The Name property of the Person class cannot be called directly.
Calculate attribute
- As the name implies, the value of the computed property is computed and does not store the value itself
- Evaluating property assignments is actually converting to other instance variables by evaluating them
To calculate the area of a square, we can calculate the area by defining an area() method that returns the length of the side * the length of the side;
void main() { var square = Square(); Square. Side = 1.5; print(square.area()); } class Square{ num side; num area() => side * side; }Copy the code
Here we can define the area as a calculated property:
void main() { var square = Square(); Square. Side = 1.5; print(square.area); } class Square { num side; num get area => side * side; }Copy the code
Area = Square; area = Square; area = Square; area = Square;
import 'dart:math';
void main() {
var square = Square();
square.side = 1.5;
print(square.area);
square.area = 36;
print(square.side);
}
class Square {
num side;
num get area => side * side;
set area(value){
side = sqrt(value);
}
}
Copy the code
The printed result is:
2.25
6.0
Copy the code
A constructor
- If no constructor is defined, there is a default constructor
- If a custom constructor exists, the default constructor is invalid
- Constructors cannot be overloaded
If you define a Person class that has no custom constructor, it will have a default constructor
class Person{
String name;
int age;
}
Copy the code
Is equal to:
class Person{
String name;
int age;
Person(){
}
}
Copy the code
When there is a custom constructor, the default constructor does not work, that is, the instance cannot be created through Person() and instead needs to be created through a constructor that takes two arguments.
class Person{ String name; int age; Person(String name, int age){ this.name = name; this.age = age; }}Copy the code
Because constructors pass parameter assignments in a common form, Dart provides a syntactic sugar form to simplify this operation, modified as follows:
class Person{
String name;
int age;
Person(this.name, this.age);
}
Copy the code
Named constructor
- With named constructors, you can implement multiple constructors
- Use the class name. Method form implementation
Since methods in Dart cannot be overridden, we can only implement multiple constructors by naming them as follows:
class Person{
String name;
int age;
Person(this.name, this.age);
Person.withName(this.name);
Person.withAge(this.age);
}
Copy the code
Three constructors are defined, two of which are named constructors that use class names. The form of the method is similar to that of the constructor when creating an instance:
Void main() {var p1 = Person(" Person ", 31); Var p2 = Person. WithName (" Person "); var p3 = Person.withAge(31); }Copy the code
Constant construction method
- If the class is immutable, you can define the object as a compile-time constant
- Declare the constructor using const, and all variables are final
- Declare an object using const, which can be omitted
Void main() {const p = Person(" 三", 18); //p = Person(" Person ", 20); Constant variables can't be assigned a value} class Person{final String name; final int age; const Person(this.name, this.age); }Copy the code
Plant construction method
- The factory construction method is similar to the factory pattern in design pattern
- Implement a factory constructor by adding the keyword factory before the constructor
- Objects can be returned in the factory constructor
void main() { var logger = Logger("tag1"); logger.log("this is a log"); } class Logger { final String 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){ print(msg); }}Copy the code
You can see that Logger contains a factory constructor, which determines whether a cached Map contains a Logger object with the specified name. If it does, it is retrieved and returned. If it does not, it is created by calling the private named constructor internal(), which is then stored into the Map and returned.
Initialization list
- The initialization list is executed before the constructor body is executed
- Initialize expressions using commas
- Initializer lists are often used to set the value of final variables
Void main() {var p = person.withname (); print("namee = ${p.name}, age = ${p.age}, gender = ${p.gender}"); } class Person{ String name; int age; final String gender; Person.withName(this.name): age = 20, gender = "female"; }Copy the code
The printed result is:
Namee = Zhang SAN, age = 20, gender = femaleCopy the code
You can see that the age and gender attributes are assigned, while gender is final and can still be assigned, indicating that the initialization list is executed before the constructor body is executed
Static members
- Use the static keyword to implement class-level variables and functions
- Static members cannot access non-static members, and non-static members can access static members
- Constants in a class need to be declared static const
void main() { Person.growUp(); Person.growUp(); Person.growUp(); } class Person{ static const int maxAge = 100; static int age = 1; static void growUp(){ age ++; print("growUp age = $age"); }}Copy the code
The printed result is:
growUp age = 2
growUp age = 3
growUp age = 4
Copy the code
Like Java, growUp is a static method that can pass through the class name. Method name directly called
Object operator
The following object operators are similar to those in Kotlin, and those with Kotlin’s experience have already got them.
- Conditional member access? .
void main() { Person person; person? .work(); } class Person{ void work(){ print("work..." ); }}Copy the code
? . Method calls are executed when the object is not null, and since the person variable is not assigned, no statements are output.
- Type conversion as
void main() {
dynamic a = "I Love Beyond";
(a as String).split(" ")
}
Copy the code
Declare a dynamic a variable and assign it to a String, but you can’t call split() directly because split() is a String method, so you need to convert it to String and call it again.
- Is! Is!
void main() { dynamic a = 1; if(a is! bool){ print("a is not bool"); } a = true; if(a is bool){ print("a is bool"); }}Copy the code
Declare a dynamic variable a, assign it to 1 and check if a is not a Boolean value at 1, because a is an int, so it will print “A is not bool”, and then assign it to true, so a is a bool, so the condition statement at 2 will satisfy, It prints “A is bool”.
Object Call method
If a class implements a call() method, objects of that class can be used as methods
void main() { var person = Person(); Person (" Huang Jiaju ", 31); } class Person{ String name; int age; void call(String name, int age){ print("name = $name, age= $age"); }}Copy the code
The printed result is:
Name = Huang Jiaju, age= 31Copy the code
Since the call() method is implemented, the object can be called directly as a method, and the call() method can also be defined to have a return value:
void main() { var person = Person(); Print (person(" person ", 31)); } class Person{ String name; int age; String call(String name, int age) => "name = $name, age= $age"; }Copy the code
This chapter has been introduced, interested partners can continue to see chapter 4:
Dart Chapter 4 — Introduction to object-oriented programming inheritance, Abstract classes, interfaces, and Mixins