Recently time is too busy, work overtime every day, but our learning behavior can not fall.
Follow me to learn the basics of the 40-minute Quickstart Dart (middle)
List of Town buildings:
In this chapter we will focus on methods and classes. These two chapters seem not much, in fact, also a lot, but friends do not worry, as long as you follow my code to knock again, to ensure that you can master most knowledge points!
All right, let’s cut the crap and get to work.
First class method object
Dart is a true object-oriented language where methods are also objects and have a type Function. This means that methods can be assigned to variables, treated as arguments to other methods, or called as arguments to another method
import 'dart:core';
void main() {
var list = ["Pharmacist Huang"."Guo jing"."Little Dragon Lady"];
void printElement(element) {
print(element);
}
list.forEach(printElement);
}
Copy the code
In Java, if you want to be able to notify the caller or other places about the execution of a method, you may need to specify an interface, which is essentially what we call a callback function. For example, onClickListener for a View. In Dart, you can specify a callback method directly to the calling method, which executes the callback at the appropriate time.
void setListener(Function listener){
listener("Success");
}
/ / or
void setListener(void listener(String result)){
listener("Success");
}
// There are two ways. The first way is that the caller is not sure what the return value and parameters of the callback function are
// The second one needs to write such a long paragraph.
A method that returns voide and takes a String is defined as a type.
typedef void Listener(StringThe result);void setListener(Listener listener){
listener("Success");
}
Copy the code
Methods can have two types of parameters in Dart: required and optional. The required parameters need to precede the parameter list, followed by the definition of optional parameters.
2. Optional named parameters
What is called an optional named function? In fact, it is called an optional named parameter by putting the parameters of the method in {}.
import 'dart:core';
void main() {
int add({int i, int j}) {
if (i == null || j == null) {
return 0;
}
returni + j; } // call with full argumentsprint("-- 1 --${add(i: 10, j: 20)}"); // Output: 30 // No arguments (call also correct)print("-- - 2${add()}"); // Output: 0 // Select pass parametersprint("--3--${add(j: 20)}"); // Output: 0 // position independentprint("--4--${add(j: 20, i: 10)}"); // Output: 30}Copy the code
3. Optional position parameters
An optional named function is a function that takes an argument to a method by placing it in [].
void main() {
int add([int i, int j]) {
if (i == null || j == null) {
return 0;
}
returni + j; } // call with full argumentsprint("-- 1 --${add(10, 20)}"); // Output: 30 // No arguments (call also correct)print("-- - 2${add()}"); // Output: 0 // Select pass parametersprint("--3--${add(10)}"); // Output: 0}Copy the code
Default parameters
The default value of an optional parameter can be defined by using = when defining a method.
import 'dart:core';
void main() {
int sum([int age1 = 1, int age2 = 2]) {
if (age1 == null || age2 == null) {
return 0;
}
returnage1 + age2; } // call with full argumentsprint("-- 1 --${sum(10, 20)}"); // Output: 30 // No arguments (call also correct)print("-- - 2${sum()}"); // Output: 3 // Select pass parametersprint("--3--${sum(20)}"); // Output: 22}Copy the code
Anonymous functions
First, what is an anonymous function?
Most methods have names, such as main() or printElement(). You can create a method without a name, call it an anonymous function, or a Lambda expression or Closure Closure. You can assign an anonymous method to a variable and then use it, such as adding the variable to or removing it from a collection.
([Type] param1,...). { codeBlock; };Copy the code
Anonymous methods look similar to named methods in that arguments can be defined between parentheses, separated by commas. The following code defines an anonymous method that takes only one parameter item and has no parameter type. This function is called for each element in the List, printing a string of element positions and values:
import 'dart:core';
void main() {
var list = ['Pharmacist Huang'.'John Steinbeck'.'Old Urchin'];
list.forEach((item) {
print('${list.indexOf(item)}: $item'); // Output: 0: Huang Yaoshi 1: Yang Guo 2: old urchiness}); // If there is only one line in the function body, you can use arrow syntax: list.foreach ((item) =>print('${list.indexOf(item)}: $item')); // Output: 0: Huang Yaoshi 1: Yang Guo 2: old urchin}Copy the code
This concludes our discussion of the common methods used to develop Flutter
In fact, the method content is more than these, the next buddy can explore: such as method scope, etc.
Let’s move on to classes
Six, class,
Dart is an object-oriented programming language. Each Object is an instance of a class, and all classes inherit from Object. It also supports object-oriented features such as classes, interfaces, abstractions, and so on.
Dart uses the class keyword to declare a DART class followed by the class name and a body surrounded by curly braces. All classes have the same base class. Object.
Class {<fields> // <getters/setters> // If the object is final, or const, and only has a getter method, which we'll have instances of later, <constructors> // Allocate memory for the object of the class <functions> // Functions, also called methods, object operations; }Copy the code
As mentioned above, the <getters/setters> method automatically generates a getter method (implicitly) for each instance variable. Non-final instance variables also automatically generate a setter method.
class User {
var name;
var age;
User(this.name, this.age);
}
void main(){
var user =User("Pharmacist Huang", 50); var _name = user.name; var _age = user.age;print("-- -- -- -- --$_name$_age"); // Output: Huang Yaoshi 50}Copy the code
Class — constructors
The Dart constructor has one implementation:
- Default constructor
- Named constructor class.name (var param)
- Call the parent class constructor
- An immutable object that defines a compile-time constant object preceded by const
- Factory constructor :factory
The default constructor is often our most common and simplest as follows
class User { var name; var age; User(this.name, this.age); // Default constructor}Copy the code
Named constructor
Dart does not support constructor overloading. Instead, it uses named constructors to implement multiple constructors for a class:
class User { var name; var age; User(this.name, this.age); // Default constructor //User(this.name); /// error because overloading user.age (this.age) {name = is not allowed"Ou Yangfeng";
}
}
void main() {
var user = User.age(50);
print("--${user.name}${user.age}"); // Output: Ouyang feng 50}Copy the code
Redirect constructor
Sometimes a constructor invokes other constructors in the class (in Java, this(…)). ). A redirection constructor has no code. After the constructor is declared, other constructors are called with colons.
class User { var name; var age; User(this.name, this.age); // The default constructor user.user (name, age) : this(name, age); } voidmain() {
var user = User.user("Pharmacist Huang", 50);
print("--${user.name}${user.age}"); // Output: Huang Yaoshi 50}Copy the code
Constant constructor
If your class provides a state invariant object, you can define these objects as compile-time constants. To do this, we need to define a const constructor and declare all class variables final.
class User { final String name; final int age; const User(this.name, this.age); // The default constructor} voidmain() {
var user = User("Pharmacist Huang", 50);
print("--${user.name}${user.age}"); // Output: Huang Yaoshi 50}Copy the code
Factory constructor
When implementing a constructor decorated with the Factory keyword, the constructor does not have to create a new instance of the class. For example, a factory constructor might take an instance from the cache and return it, or return an instance of a subtype. (Factory constructor cannot access this)
If a constructor does not always return a new object, use factory to define the constructor. class Logger { final String name; bool mute =false;
static final Map<String, Logger> _cache = <String, Logger>{};
factory Logger(String name) {
if (_cache.containsKey(name)) {
return _cache[name];
} else {
final logger = new Logger._internal(name);
_cache[name] = logger;
return logger;
}
}
Logger._internal(this.name);
void log(String msg) {
if(! mute) {print(msg); }}} // call voidmain() {var logger = new logger ()'UI');
logger.log('Button clicked');
}
Copy the code
Final logger = new logger._internal (name); final logger = new logger._internal (name); In the factory constructor above, if there is a key value for the passed name in the cache, the corresponding value from the cache is returned. If not found in the cache, a new object is created using the named constructor, cached and returned
Note: Singleton can be implemented with the help of factory constructors: (Practical scenario: Flutter network request Dio application)
Class DioUtil {static final dioutil_instance = dioutil._init (); static Dio _dio; factoryDioUtil() {
return _instance;
}
DioUtil._init() { _dio = new Dio(); }}Copy the code
Eight, methods,
Above are methods: Methods are functions that provide behavior for objects.
Getters and Setters
Dart implicitly has a getter for each instance variable, and a setter if the variable is not final. You can create new properties by implementing getters and setters, defining getters and setters using the get and set keywords:
class Rect { num left; num top; num width; num height; Rect(this.left, this.top, this.width, this.height); Num get right => left + width;set right(num value) => left = value - width;
}
void main() {
var rect = Rect(0, 0, 10, 10);
print(rect.right); //10
rect.right = 15;
print(rect.left); / / 5}Copy the code
The advantage of using getters and setters is that you can use your instance variables and wrap them in methods over time without changing any code, meaning that you define them and then change them without affecting the original logic.
Abstract classes, abstract methods, and inheritance
Instance methods, getters, and setters can all be abstract. Defining an interface method without implementing it lets the class that implements it implement that method. Abstract methods can only exist in abstract classes, whose definitions are similar to Java abstract classes.
abstract class User { void say(); } class Person extends User{@override voidsay() {// provide an implementation, so here the method is no longer abstract... }}Copy the code
Note: Abstract classes cannot be instantiated unless factory methods are defined and subclasses are returned.
abstract class User { String name; // The default constructor User(this.name); // The factory method returns the Child instance factory user.test (String name){return new Child(name);
}
void printName(); Class Child extends User{Child(String name) : super(name); @override voidprintName() {
print(name);
}
}
void main() {
var p = User.test("Pharmacist Huang");
print(p.runtimeType); // Print the actual type Child p.prinname (); // Output the actual type huang Yaoshi}Copy the code
Ten, interfaces,
Dart does not use the Java interface keyword to define an interface. A class declared in class is an interface. You can implement one or more interfaces using the implements keyword and implement the API defined for each interface:
The Person class contains the greet() method in its implicit interface. The class User {// _name variable is also included in the interface, but it is only visible in the library. final _name; // The constructor is not in the interface. User(this._name); // Greet () on the interface. String greet(String who) =>'Hello, $who. I am a $_name. '; } // An implementation of the Person interface. class Impostor implements User { get _name =>' ';
String greet(String who) => 'Hello $who. Do you know who I am? ';
}
String greetBob(User person) => person.greet('Pharmacist Huang');
void main() {
print(greetBob(User('Ouyang Feng'))); // Output: Hello, Huang Yaoshi. I am Ouyang Feng.print(greetBob(Impostor())); // Output: Hello huang Yaoshi. Do you know who I am? }Copy the code
Then the question comes, what is the difference between the interface and inheritance, is not more than inheritance? The implementation of an interface means that subclasses get only the member variable symbols and method symbols of the interface, and need to reimplement the member variables and declare and initialize the methods, otherwise the compiler will report an error. Inheritance can choose not to be reimplemented, which is the biggest difference.
May small partners feel a little round: that we sum up. In two words:
- Single inheritance, multiple implementations.
- Inheritance can optionally override superclass methods and can use super to enforce a redefinition of all interface members.
Xi. Callable classes:
If the Dart class implements the call() function, it can be called as a method.
class User {
call(String name, int age) => '$name $age! ';
}
main() {
var c = new User();
var out = c("Pharmacist Huang", 50);print(out); // output: Huang Yaoshi 50! }Copy the code
Mixing Mixins
In the object-oriented world, we are most familiar with class, Abstract class, and Interface. Dart is a modern object-oriented programming language with new features such as Mixins
What are Mixins:
Simple to understand, is used to reuse code between multiple classes, reduce coupling. Let’s go straight to an example.
In the days before Mixins:
Let’s say we’re developing a complete animal App and we need to create a Duck class. As a developer with extensive object-oriented programming experience, you naturally extract all features similar to Duck into an Abstract class.
/// Bird
abstract class Bird {
void shout() {
println('shouting');
}
}
/// WaterborneBird
abstract class WaterborneBird extends Bird {
void swim() {
println('swimming');
}
}
/// Duck
class Duck extends WaterborneBird {
void doDuckThings() {
shout();
swim();
println('quack quack quack! ')}}Copy the code
Well, we clearly classify ducks as aquatic birds, and it becomes very easy to add other birds. But now we need to add the goldfish, so we write the same code as above.
/// Fish
abstract class Fish {
void swim() {
println("swimming")
}
}
/// GoldFish
class GoldFish extends Fish {
void doGoldFishThings() {
swim();
pringln('zzz... '); }}Copy the code
This is where we find that goldfish and ducks have swim properties, which is very simple in this case, but if we have complex behaviors that need to be assigned to a new class, we have to write a lot of repetitive code.
Use Mixins
We declare a Swimming mixin:
mixin Swimming {
void swim() {
println('swimming')}}Copy the code
We can use the with keyword to add mixins to the class, and you might recall that we’ve already used the with keyword. Now we can modify the above code:
/// Bird
abstract class Bird {
void shout() {
println('swimming');
}
}
/// Duck
class Duck extends Bird with Swimming {
void doDuckThings() {
shout();
swim();
println('jump! ')}}Copy the code
/// Fish
abstract class Fish {
}
/// GoldFish
class GoldFish extends Fish with Swimming {
void doGoldFishThings() {
swim();
pringln('zzz... '); }}Copy the code
Mixins make up for the lack of interfaces and inheritance, which can only be inherited singly, whereas interfaces cannot be implemented repeatedly, mixins can be mixed and can take advantage of mixins classes.
Let’s look at an example for comparison:
abstract class Swimming{
void swimming() {print("Swimming");
}
}
abstract class Jump{
void jump() {print("Jump"); }} class HuangYaoShi extends Swimming implements Jump{// Implements voidjump() {print("Jump"); Class HuangYaoShi with Swimming, Jump {} Class HuangYaoShi with Swimming, Jump {}Copy the code
There are many more things to note about Mixins, and while Mixins can be used to simplify the code, it should be based on an accurate understanding of the relationship between requirements and classes. Take a look at some of the source code for Flutter implementation using Mixins to learn the right lessons.
Next chapter: 40 minute Quick Start Dart Basics (Ii)
Reference: The animal example above reprints the blogger’s article: In-depth Understanding of Dart Mixins
Finally attached: tool library collected by myself (to be completed) Tool library – to be completed
Dart: How can I quickly master the Dart language and progress to become the God of Flutter