Recently, I relearned Dart with my mobile friends. I mainly watched the CoderWhy video tutorial, which was very good, and made some notes
Variable declarations
/* * * ** * * ** * * *支那* Declare variables* * * ** * * ** * * ** * * ** * /
void defineVariable() {
// Variable declaration (var/final/const)
// var Declares variables
var age = 20;
// age = "abc";
age = 30;
// final declares constants
final height = 1.88;
// const declares a constant
const address = Shenzhen City;
// Final and const
// const date1 = DateTime.now(); Write error
final date2 = DateTime.now();
// 📢 After Dart 2.0, const can be omitted
const p1 = const Person("hello");
const p2 = const Person("world");
const p3 = const Person("zhengzeqin");
print(identical(p1, p2)); // true
print(identical(p2, p3)); // false
// 📢 After Dart 2.12, the default optional type requires? Previously, the default was not added
String? optionName = null;
optionName = "zhengzeqin";
}
Copy the code
Final vs. const
- Const must assign a constant value (a certain value is required at compile time)
- Final can obtain a value by evaluating/functions (to determine a value at run time)
runtimeType
RuntimeType: Used to get the current type of a variable
var name = 'zhengzeqin';
print(name.runtimeType); // String
Copy the code
The use of dynamic
Similar to swift Any, declare dynamic variables
question
Difference between Dynamic and Object?
// The difference between Object and dynamic
// The superclass application points to the subclass object
/ / Object and dynamic
// Object calls a method, an error is reported at compile time
// dynamic calls the method without error at compile time, but there are security risks at run time
// Error example
Object obj = "why";
print(obj.substring(1));
// Explicitly declare
dynamic obj2 = 123;
print(obj2.substring(1));
Copy the code
identical
Const const const const const const const const const const const const const const const const const const
// after Dart2.0, const can be omitted
const p1 = const Person("hello");
const p2 = const Person("world");
const p3 = const Person("zhengzeqin");
print(identical(p1, p2)); // true
print(identical(p2, p3)); // false
class Person {
final String name;
const Person(this.name);
}
Copy the code
The data type
Numeric types
int double
string
/* * * ** * * ** * * *支那* string* * * ** * * ** * * ** * * ** * /
void stringFunction() {
// 1. How to define a string
var s1 = 'Hello World';
var s2 = "Hello Dart";
var s3 = 'Hello\'Fullter';
var s4 = "Hello'Fullter";
// 2. The way to represent multi-line strings
var message1 = "Ha ha ha ha ha ha ha ha ha ha ha ha ha;
print('my name is ${message1}');
// 3. Splice other variables
var name = 'zhengzeqin';
var age = 18;
var height = 1.88;
print('my name is ${name}, age is $age, height is $height');
}
Copy the code
Boolean type
There is no non-zero or true
Dart declares that there is no non-zero or true case of a variable
var flag = "abc";
if (flag) { // Error example
print("Execute code");
}
Copy the code
string
- Support “”, “””” “””
- “”” “”” supports line breaks
- ${variable}, then {} can be omitted, if the function or expression calculation need not be omitted
/ / string
void stringFunction() {
// 1. How to define a string
var s1 = 'Hello World';
var s2 = "Hello Dart";
var s3 = 'Hello\'Fullter';
var s4 = "Hello'Fullter";
// 2. The way to represent multi-line strings
var message1 = "Ha ha ha ha ha ha ha ha ha ha ha ha ha;
print('my name is ${message1}');
// 3. Splice other variables
var name = 'zhengzeqin';
var age = 18;
var height = 1.88;
print('my name is ${name}, age is $age, height is $height');
}
Copy the code
A collection of
Dart has three of the most common ones built in: List/Set/Map
- The two biggest differences between a Set and a List are that a Set is unordered and its elements are not repeated.
void collectFunction() {
/ / the List definition
// 1. Use type derivation for definitions
var letters = ['a'.'b'.'c'.'d'];
print('$letters ${letters.runtimeType}');
// 2. Specify the type explicitly
List<int> numbers = [1.2.3.4];
print('$numbers ${numbers.runtimeType}');
The two biggest differences between a Set and a List are that a Set is unordered and its elements are not repeated.
// 1. Use type derivation for definitions
var lettersSet = {'a'.'b'.'c'.'d'};
print('$lettersSet ${lettersSet.runtimeType}');
// 2. Specify the type explicitly
Set<int> numbersSet = {1.2.3.4};
print('$numbersSet ${numbersSet.runtimeType}');
numbers = Set<int>.from(numbers).toList();
print(numbers);
// Add/remove/include elements
numbers.add(5);
numbersSet.add(5);
print('$numbers $numbersSet');
numbers.remove(1);
numbersSet.remove(1);
print('$numbers $numbersSet');
print(numbers.contains(2));
print(numbersSet.contains(2));
// List deletes elements according to index
numbers.removeAt(3);
print('$numbers');
// Map definition
// 1. Use type derivation for definitions
var infoMap1 = {'name': 'harden'.'age': 18};
print('$infoMap1 ${infoMap1.runtimeType}');
// 2. Specify the type explicitly
Map<String.Object> infoMap2 = {'height': 1.88.'address': 'Shenzhen'};
print('$infoMap2 ${infoMap2.runtimeType}');
// Map operation
// 1. Obtain value based on key
print(infoMap1['name']); // harden
// 2. Get all entries
print('${infoMap1.entries} ${infoMap1.entries.runtimeType}'); // (MapEntry(name: why), MapEntry(age: 18)) MappedIterable<String, MapEntry<String, Object>>
// 3. Get all keys
print('${infoMap1.keys} ${infoMap1.keys.runtimeType}'); // (name, age) _CompactIterable<String>
// 4. Get all values
print('${infoMap1.values} ${infoMap1.values.runtimeType}'); // (harden, 18) _CompactIterable<Object>
// 5. Check whether a key or value is included
print('${infoMap1.containsKey('age')} ${infoMap1.containsValue(18)}'); // true true
// 6. Delete elements based on key
infoMap1.remove('age');
print('${infoMap1}'); // {name: harden}
}
Copy the code
question
- Is there anything wrong with this?
var info<String.Object> = {
"name": "why"."age": 18
};
Copy the code
- var names = [“abc”, “cba”, “nba”, “cba”]; How do I write this if I need to specify the type?
function
Return value The name of the function (argument list) {function bodyreturnThe return value}Copy the code
Optional parameters
Optional parameters can be classified into named optional parameters and location optional parameters
- 📢 Location Optional: The corresponding sequence must be correct
- Dart has no function overloading
Name Optional parameters: {param1, param2... } Position Optional parameters: [param1, param2,...]// Optional: Location optional - Name optional
// Note: Only optional parameters can have default values
// Position optional: [int age, double height]
// Arguments and parameters are matched by position
void sayHello1(String name, [int age = 10.double height = 2.int money = 0]) {
print("sayHello1 name: $name age: $age age: $height money: $money");
}
// Naming is optional
void sayHello2(String name, {int age = 10.double height = 3.14{})print("sayHello2 name: $name age: $age age: $height");
}
Copy the code
question
Position optional Parameters Optional parameters, must be in order to pass parameters? What if you only want to pass the money parameter and do not want to pass other parameters?
The function is a first-class citizen
A function can be assigned to a variable or used as an argument or return value of another function
void firstFunction() {
// 1. Find another defined function and pass it in
// test(bar);
// 2. Anonymous function (argument list) {function body};
translationFunc(() {
print("Anonymous function called");
return 10;
});
var movies = ['Infernal Affairs 1'.Infernal Affairs 2.'Infernal Affairs 3'];
// Use forEach to traverse: named functions
printElement(item) {
print(item);
}
movies.forEach(printElement);
// Use forEach to traverse: anonymous function
movies.forEach((item) {
print(item);
});
movies.forEach((item) => print(item));
// 3. Arrow function: conditional, function body has only one line of code
translationFunc(() => print("Arrow function executed."));
// 4. Using aliases to define parameters requires: pass in a function & anonymous function
calculateFunc((num1, num2) {
return num1 * num2;
});
// 5. Declare the function and call it
var add = addFunc();
print(add(20.30));
}
// A function can be an argument to another function
void translationFunc(Function foo) {
foo();
}
void bar() {
print("Bar function called");
}
// Use aliases to define function types
typedef Calculate = int Function(int num1, int num2);
void calculateFunc(Calculate calc) {
calc(20.30);
}
Calculate addFunc() {
return (num1, num2) {
return num1 * num2;
};
}
Copy the code
question
Does the arrow function support multiple lines?
The operator
conditions
?? =
: When the variable isnull
, use the following content for the assignment, otherwise no assignment??
: When the variable isnull
, the following value is used, otherwise the value of the variable is used
void conditionalOperatorFunc() {
/ / 1.?? = :
// When the original variable has a value, then?? = does not perform
// If the original variable is null, then assign the value to the variable
var name = null; name ?? ="harden";
print(name);
/ /?? :
/ /?? If the previous data has a value, use?? Previous data
/ /?? If the previous data is NULL, the later value is used
var name2 = null;
var temp = name2 ?? "harden";
print(temp);
}
Copy the code
cascade
.
: similar to chain call
class Animal {
String? name;
Animal(this.name);
void run() {
print("running");
}
void eat() {
print("eating"); }}// cascade operator
void cascadeOperatorFunc() {
// cascade operator
var p = Animal("zhengzeqin")
..name = "harden". eat() .. run(); }Copy the code
Process control
if else
for
while
do-while
break
continue
switch-case
Copy the code
void processControlFunc() {
for (var i = 0; i < 5; i++) {
print(i);
}
var names = ['harden'.'kobe'.'curry'];
for (var name in names) {
print(name);
}
var direction = 'east';
switch (direction) {
case 'east':
print('the east');
break;
case 'south':
print('the south');
break;
case 'west':
print('the west');
break;
case 'north':
print('the north');
break;
default:
print('Other direction'); }}Copy the code
Classes and objects
A constructor
- When a constructor is not explicitly specified in a class, it defaults to having a constructor with no arguments.
- 📢 After Dart 2.12, the default optional type requires? Otherwise, the default no-argument constructor will not compile
- 📢 When you have your own constructor, the default constructor is invalidated and cannot be used
- Of course, you might want to explicitly write a default constructor, but that would conflict with our custom constructor;
- This is because Dart itself does not support function overloading (the same name, different arguments)
- Named constructors: custom named constructors
- Initializer list: the constructor body initializes the instance variable before it runs. The initializer list can be used
- Redirected constructor: You can use a redirected constructor when you want to call another constructor from within a constructor
- Constant constructor: We refer to the final section when we pass in the same value and want to return the same object
- Factory constructor: Dart provides the Factory keyword to retrieve objects from the factory
void classFunc() {
var hunman = Human(12);
print("hunman: $hunman");
}
class Runner {
// 📢 After Dart 2.12, the default optional type requires? Otherwise, the default no-argument constructor will not compile
String? name;
int? age;
}
class Human {
// 📢 After Dart 2.12, the default optional type requires? Otherwise, the default no-argument constructor will not compile
String? name;
int? age;
// Human(String name, int age) {
// this.name = name;
// this.age = age;
// }
// 📢 defaults to a no-fail constructor. If you declare a parameter constructor, the system default no-argument constructor does not exist
// Human(this.name, this.age); // Syntax sugar equals comment section
// Initialize the list page
Human(this.age) : name = "zhengzeqin age is $age";
// Name the constructor
Human.withArgments(String name, int age) {
this.name = name;
this.age = age;
}
// Name a redirection constructor
Human.form(int age) : this(age);
// constant constructor
// Project constructor, 📢 If there is a constructor of the same name, the factory constructor can no longer be implemented
// factory Human(Int age) {
// return Human.withArgments("zhengzeqin", age);
// }
// setter && getter
String? get getName {
return name;
}
set setName(String name) {
this.name = name;
}
@override
String toString() {
return 'name=$name age=$age'; }}Copy the code
An abstract class
- Abstract methods must exist in abstract classes
- Abstract classes are classes that use abstract declarations
- 📢 If there is an implementation body, the implementation class may not implement the abstract method
/ / abstract classes
abstract class Shape {
double getArea();
// 📢 If there is an implementation body, the implemented class may not implement the abstract method
void getName() {}
}
class Circle extends Shape {
double? r;
Circle(this.r);
@override
getArea() {
final rr = r ?? 0;
return rr * rr * 3.14; }}class Reactangle extends Shape {
double w = 0;
double h = 0;
Reactangle(this.w, this.h);
@override
getArea() {
returnw * h; }}Copy the code
Implicit interface
- Dart interfaces are special and do not have a specific keyword to declare them.
- By default, each class defined also declares an interface by default that can be implemented by other classes (because Dart does not support multiple inheritance).
- 📢 When a class is used as an interface, the class that implements the interface must implement all methods in the interface
- Extends extends a class, while implements an interface
abstract class Player {
play();
}
abstract class Flyer {
fly();
}
class SuperManer implements Player.Flyer {
@override
play() {
print('Superman is playing');
}
@override
fly() {
print('Superman is flying'); }}Copy the code
Mixin
- In addition to defining a class through class, you can also define a class through the mixin keyword.
- Mixin-defined classes are used to be mixed with other classes, but mixed with with the with keyword is equivalent to multiple inheritance
// implements requires that methods be re-implemented, whereas with does not
// Mix mixin classes with the with method, equivalent to multiple inheritance
// The on keyword specifies that subclasses of the class can use the current mixin (without the default limiting to Object).
mixin Runing {
var name = "";
run() {
print('On the run'); }}mixin Flying {
fly() {
print('Flying'); }}class SuperWoman with Flying.Runing {
void sayHello() {
print("hello my name is $name"); }}Copy the code
The generic
List and Map generics
Does the user want to use an int, a double, or even a string?
- One solution is to use Object and dynamic, but it’s very inconvenient to use them later
- The alternative is to use generics.
void genericFunc() {
// Restrict the type
var names1 = <String> ['harden'.'kobe'.'james'];
List<String> names2 = ['harden'.'kobe'.'james'];
// Display the type
Map<String.dynamic> infos1 = {'name': 'harden'.'age': 18};
var infos2 = <String.dynamic> {'name': 'harden'.'age': 18};
}
// specify that T is derived from the num class
class Location<T extends num> {
T x;
T y;
Location(this.x, this.y);
}
Copy the code
The use of libraries
- Import ‘library URL ‘;
- Dart: prefix indicates the standard library for dart, such as DART: IO, DART: HTML, dart: mathImport ‘DART: IO’.
- Of course, you can also reference import ‘lib/student/student.dart’ in relative or absolute path dart files;
- Import ‘lib/student/student.dart’ as Stu;
- You can use the show and hide keywords if you want to import only certain content from the library, or if you want to hide certain content from the library
- import ‘lib/student/student.dart’ show Student, Person;
- import ‘lib/student/student.dart’ hide Person;
export
- Import multiple libraries through export
Code sample
- portal
reference
- Dart (1)
- Dart (2)