preface
Some time ago, I summarized some basic knowledge of Dart when I systematically studied Flutter. There are a lot of things in Dart. I suggest that you save them and slowly read π. A link to a previous article should give you a better understanding of Dart asyncrony: The details of Dart that you didn’t know about will give you a better understanding of asyncrony. This is the version of Flutter that I wrote about Flutter some time ago. If you are interested, you can go to see it. It is very suitable for Flutter beginners: it took three days to complete the version of Flutter. Dart variables, built-in types, functions (methods), flow control statements, exception handling, classes, generics, libraries, etc. Are you ready? To drive, please fasten your safety belt πΆ, the speed is fast, please don’t get off halfway!!
variable
Hello World
Learning a language typically starts with printing “Hello World,” so here’s how to print in Dart:
void main(){
print("Hello World");
}
Copy the code
Dart, like Java, requires a main method, so printing is a little easier. Note that void can be omitted if the method does not return a value
Declaration of variables
Really getting to the point… Dart has three keywords for variable declaration: var, Dynamic, and Object. The three keywords are used differently. Let’s say it separately:
var
In Kotlin, var means a variable that is mutable (val means immutable, equivalent to final). In Dart, var can be of any type if it has no initial value, but if it has an initial value, Then the type will be locked. What does that mean? Take a look at the following code to see why:
main(){
//print("Hello World");
var data;
data = 'zhujiang';
data = 123;
print(data);
}
Copy the code
Var can be arbitrarily typed without an initial value, such as the above code, which can be either a string or an int. Note here: Dart strings can be quoted in either single or double quotes.
This code does not assign an initial value, so let’s see:
main(){
//print("Hello World");
var data = 1;
data = 'zhujiang';
data = 123;
print(data);
}
Copy the code
As you can see, if you have an initial value, you can’t change the type, which confirms what we said above about the type being locked.
Object
The superclass of all objects in Java is Object. In Dart, dynamic refers to dynamic type, which is checked at compile time. Object, unlike var, can also specify other types even if an initial value is assigned:
Object data2 = 1234;
data2 = 'dongnao';
print(data2);
Copy the code
This means that if you call a method that doesn’t already have one, you can call it in red to alert you to an error. (Var also checks for types at compile time.)
dynamic
I had not seen this keyword in other languages before I learned Dart, so it was unfamiliar to me. This keyword is very similar to Object, with the only difference being that the type is not checked during compilation. As opposed to Object, if you call a method that doesn’t already have an exception, no error is reported, but an exception is thrown when you run it.
The default value of a variable
This did not want to say, but found and learned before is not quite the same, or to say.
In Dart, variables that are not initialized automatically get a default value of NULL
Everything is an object, and the default value of an object is NULL
Just keep in mind the above two statements, and don’t get caught up in Java. For example, Boolean defaults to false, but bool defaults to null in Dart. Remember, everything is an object, and objects default to NULL
The variables final and const
Final everyone know, often used in Java, const relative is a stranger, said the below what they have in common:
-
The declared type can be omitted
final fVariable1 = 'zhujiang'; // final String fVariable1 = 'zhujiang'; const cVariable1 = 'zhujiang'; // const String cVariable1 = 'zhujiang'; Copy the code
-
No more assignment after initialization
fVariable1 = 'demo'; cVariable1 = 'demo'; Copy the code
After the above initialization, no assignment can be made here, and an error will be reported if an assignment is made
-
Cannot be used together with var
final var fVariable1 = 'zhujiang'; const var fVariable1 = 'zhujiang'; Copy the code
If used with var, an error will be reported.
Here’s another look at the differences:
-
Class level constants, using static const
static const int monday = 1; Copy the code
Here you can look at classes in the system, such as DateTime.
-
Const can initialize its value with the value of another const constant
const width = 100; const height = 100; const square = width * height; Copy the code
-
Use a const assignment declaration, const can be omitted
const List clist = [1.2.3]; // const List clist = const [1, 2, 3]; Before dart 2, const assignments must be declared as const Copy the code
-
You can change the value of a non-final, non-const variable, even if it once had a const value
var varList = const [1.2.3]; final finalList = const [1.2.3]; const constList = [1.2.3]; varList = [1]; // constList = [1]; // finalList = [1]; Copy the code
-
Immutability resulting from const is transitive
final List ls = [1.2.3]; ls[1] = 4; print(ls); const List ls1 = [1.2.3]; // ls1[1] = 4; Copy the code
-
The same const constant is never created twice in memory
final finalList1 = [1.2]; final finalList2 = [1.2]; print(identical(finalList1, finalList2)); //identical is used to check whether two references refer to the same object const constList1 = [1.2]; const constList2 = [1.2]; print(identical(constList1, constList2)); Copy the code
The results of the above code are false and true.
-
Const needs to be a compile-time constant
final DateTime finalDateTime = DateTime.now(); // const DateTime constDateTime = DateTime.now(); // datetime.now () is the value calculated at runtime Copy the code
A small summary
This section briefly explains some of the details of variables in Dart. If there are any additions or errors, please feel free to comment directly in the comments section π.
Built-in types
An overview of the
In Dart, there are several built-in types: Numbers, Strings, Booleans, Lists, Sets, Maps, Runes symbolic characters, and Symbols identifiers.
num, int, double
Int is an integer and double is a 64-bit double. We need to focus on num here. Int and double are subclasses of num. Num = num; num = num; num = num;
int i = 1; / / integer value
double d = 1.0; // Double 64-bit floating point number
int bitLength = i.bitLength;
print('bitLength: ${bitLength}'); //bitLength Determines the number of bits required for an int value
double maxFinite = double.maxFinite;
print('maxFinite: ${maxFinite}'); // The maximum value of maxFinitedouble
//int and double are subclasses of num
num n1 = 1;
num n2 = 1.0;
// Supports decimal and hexadecimal numbers
int i1 = 0xfff;
// Scientific notation
double d1 = 1.2 e2; / / 120.0
/ / conversion
//String->int
int i2 = int.parse('1');
double d2 = 1; // When double is an int, int is automatically converted to double
print('d2: ${d2}');
// int i2 = int. TryParse ('1.0'); / / returns null
Copy the code
String
-
The Dart string is a UTF-16-encoded sequence of characters that can be created using either single or double quotation marks
main(){ String a = 'zhujiang'; String b = "zhujiang"; } Copy the code
-
You can create a multi-line string object using three single or double quotation marks
String c = "dd" "sssdffg" "vftgt"; String d = '''ssss fffffffgg grrrr'''; Copy the code
-
You can use the r prefix to create a “raw” string.
String e = '''ssss fff\nffffgg grrrr'''; String f = r'''ssss fff\nffffgg grrrr'''; print(e); print(f); Copy the code
It is important to note that if the r prefix is used, i.e. the raw string, the newline \n will be printed without newline implementation. Here is the result:
lib/2-type.dart: Warning: Interpreting this as package URI, 'package:darttest/2-type.dart'. ssss fff ffffgg grrrr ssss fff\nffffgg grrrr Copy the code
-
You can use an expression in a string: ${expression}. If the expression is an identifier, you can omit {}. If the result of the expression is an object, Dart calls the object’s toString() function to get a string.
print("object:$c"); Copy the code
Now that we’re talking about strings, let’s go back to StringBuffer, which uses the same method as Java, but can omit the new keyword and make chained calls:
StringBuffer stringBuffer = StringBuffer(a); stringBuffer.. write("sss").. write("ssss");
Copy the code
bool
Bool is equivalent to Boolean in Java, just remember that the default value for bool objects is null (as mentioned in the previous article).
List
-
Dart can print a list directly, including elements of a list, which is also an object. (In Java, printing a list directly results in an address value.)
print(List) Copy the code
I’m just going to print the List.
-
The subscript index of a List in Dart starts at 0, as in Java
-
Generics are supported as in Java.
-
Add, delete, change, check, support reverse order, own sort, shuffle, you can use + to merge two lists
// Add, delete, change, sort, shuffle, copy sublist var list4 = []; / / to add list4.add(1); print('add 1 :${list4}'); / / delete list4.remove(5); print('remove 5 :${list4}'); list4.removeAt(2); print('remove at 0 :${list4}'); / / change list4[4] = 5; print('update list4[4] to 5 :$list4}'); //range list4.fillRange(0.3.9); print('fillRange update list4[0]-list4[2] to 9 :$list4}'); ε―θΏδ»£ getRange = list4.getRange(0.3); print('getRange list4[0]-list4[2] :$getRange}'); / / check var contains = list4.contains(5); print('list4 contains 5 :${contains}'); var indexOf = list4.indexOf(1); print('list4 indexOf 1 :${indexOf}'); int indexWhere = list4.indexWhere((test) => test == 5); print('list4 indexWhere 5 :${indexWhere}'); / / sorting list4.sort(); print('list4 sort :${list4}'); / / shuffle list4.shuffle(); print('list4 shuffle :${list4}'); // Copy the sublist var list5 = list4.sublist(1); print('sublist(1) list5 :${list5}'); / / operators var list6 = [8.9]; print('list6 :${list6}'); var list7 = list5 + list6; print('list5 + list6 :${list7}'); Copy the code
Here the code is longer, but very easy to understand, is a collection of add, delete, change, check and some more commonly used methods, you can write their own to deepen understanding.
Map
Map, which I won’t talk about here, is similar to Java
Set
Set is similar to Java, but with a few caveats:
- Set1.difference (set2): Returns the set of elements present in set1 but not in set2
- Set1. intersection(set2) : Returns the intersection of set1 and set2
- Set1. union(set2) : Returns the union of set1 and set2
- Set1.retainall () : set1 only preserves certain elements (the elements to be retained must exist in the original set)
These methods are very easy to use, write a simple pseudo-code for you to see:
var difference12 = set1.difference(set2);
var difference21 = set2.difference(set1);
print('set1 difference set2 :${difference12}'); // return the set of elements present in set1 but not in set2
print('set2 difference set1 :${difference21}'); // return the set of elements present in set2 but not in set1
var intersection = set1.intersection(set2);
print('set1 set2 intersection:${intersection}'); // return the intersection of set1 and set2
var union = set1.union(set2);
print('set1 set2 union:${union}'); // return the union of set1 and set2
set2.retainAll(['aa'.'flutter']); // Retain only (the element to be retained must exist in the original set)
print('set2 only retains AA flutter:${set2}');
Copy the code
Runes
Represents the meaning of a rune, used to represent Unicode characters in strings. Display character graphs using string.fromCharcodes. If it is not four values, you need to put the encoded value in braces.
Runes Runes = new Runes('\u{1f605} \ 11 '); var str1 = String.fromCharCodes(runes); print(str1);Copy the code
Just write it like this, and let’s see what it looks like:
π
ICopy the code
Emoticons can be printed directly, and Runes can be used directly for emoticons.
Symbol
The mirrors module has been removed, so the mirrors module is not used anymore. As long as you know there is a built-in type for mirrors, you can use the Symbol identifier.
methods
The method part is very important, write code without method ah, keep driving, hold on!
define
-
Can be defined within a function
void main(){ void test(){ } } Copy the code
Unlike Java, Dart functions can be defined inside functions (confused with Java’s anonymous inner classes)
-
Omit types when defining functions (not recommended)
main(){ test(){ // return null;}}Copy the code
Dart functions are objects of type Function. All functions return a value. If no return value is specified, the statement returns NULL by default. Execute as the last statement of the function.
-
Support for abbreviation syntax => (Kotlin implements it with =)
main(){ print(test1()); } test()=> "zhujiang"; String test1(){ return "zhujiang"; } Copy the code
Test () and test1() have the same effect in the code above, with “=>” equivalent to curly braces and return
Optional parameters
Since it is a function, then must pass the parameter, I after the destruction of the Java constructor, when seeing this function in tears π. Why is that? Let’s start with a constructor for our Java class:
public class Test {
private String name;
private int age;
private String address;
public Test(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
public Test(String name, String address) {
this.name = name;
this.address = address;
}
public Test(String name, int age) {
this.name = name;
this.age = age;
}
public Test(String name) {
this.name = name; }}Copy the code
A very simple constructor, just want to pass the argument a little bit more form, actually need to write so many overloaded methods… So let’s take a look at the code that does the same thing with Dart:
class Test{
String name;
int age;
String address;
Test(this.name, {this.age, this.address});
}
Copy the code
What? How could that be? Yes, you can. Let’s look at the function’s optional arguments in more detail.
Optional named parameter
In fact, I use the above constructor as an optional named parameter, which is actually very easy to write, just need to put curly braces. Here’s how to use it:
main() {
print(add(a: 1, b: 3));
}
int add({int a = 1.int b}) {
return a + b;
}
Copy the code
The add method above can be called with no arguments, with any argument, or with all arguments. Note here:
- The default value is 1 if a is left blank, and null if B is left blank.
- Remember to write a: when passing parameters, otherwise an error will be reported.
Optional position parameter
Unlike the optional named arguments above, which must be named and used with a colon, the optional positional arguments are not required. Here, as above, the default value can be added or not:
int add2(int a,[int b = 2.int c = 3]) {
return a + b;
}
Copy the code
Here are a few ways to call the add2() method above:
print(add2(1));
print(add2(1.2));
print(add2(1.1.3));
Copy the code
Pay attention to
The above optional named and optional positional arguments can use list or map as defaults, but must be const.
int add3({List a = const [1.2.3].int b = 2{})return b;
}
Copy the code
Anonymous functions
Can be assigned to a variable and called by a variable. Can be called directly from or passed to other functions. Anonymous functions are divided into anonymous functions with no parameters and anonymous functions with parameters:
-
Anonymous function without parameters
var printFun = () => print("** Anonymous function without arguments **"); Copy the code
-
Parameter anonymous function
var printFun2 = (name) => print("** anonymous function $name**"); printFun2("sss"); Copy the code
One more tip: it can be called by (), not recommended.
(() = >print("*** can be called by () without pushing"()));Copy the code
closure
There is nothing to say here, but you can understand it by looking directly at the code:
Function makeAddFunc(int x) {
x++;
return (int y) => x + y;
}
var makeAddFun = makeAddFunc(11);
print(makeAddFun(10));
Copy the code
It creates a method and returns a method that can be called again.
Function is an alias
Use a typedef to give a function an alias that is convenient to use. For example, to define a method callback, use the alias definition directly. If no value is returned, as long as the parameters match, if a return value is defined, an error will be reported if the return value is different.
typedef Fun1(int a, int b);
typedef Fun2<T, K>(T a, K b);
int add(int a, int b) {
print('a + b');
return a + b;
}
class Demo1 {
Demo1(int f(int a, int b), int x, int y) {
var sum = f(x, y);
print("sum1 = $sum"); }}class Demo2 {
Demo2(Fun1 f, int x, int y) {
var sum = f(x, y);
print("sum2 = $sum"); }}class Demo3 {
Demo3(Fun2<int.int> f, int x, int y) {
var sum = f(x, y);
print("sum3 = $sum"); }}Copy the code
The above code is the method that defines the alias of the function, and the following is the method that calls it:
Fun1 fun1 = add(11.12);
Copy the code
Operators, process control statements, exceptions
This section might seem like a lot, but it’s actually quite simple, and a lot of it is basically Java consistent.
The operator
Dart operators in black are almost the same as those in Java, so let’s take a closer look at operators that are not in red in Java:
-
Postfix operation:? .
If you have written Kotlin, you can skip this paragraph. The question mark here is basically the same as Kotlin, which is used for short call.
main() { String a; print(a.length ! =null ? a.length : ' '); } Copy the code
Above is the code we usually write, a ternary expression to judge empty. But in Dart you don’t have to do that, you can just use question marks.
main() { String a; //print(a.length ! = null ? a.length : ' & # 39;) ; print(a? .length); }Copy the code
Is it convenient? Later short can be directly used **”? . “* *
-
Divide (round) : ~/
This operator is actually very simple, just round the number, here is an example code:
print(1/2); print(1~ /2); Copy the code
The output values of the above code are 0.5 and 0
-
Type operation: AS
This is basically the same as Kotlin’s AS, it is very simple, directly look at the code:
num n = 1; int n2 = n as int; Copy the code
-
Type operation: is
num n1 = 1.0; if(n1 is int) {print("int"); }else{ print("double"); } Copy the code
-
Type operation: is!
As you can see from the name, this is the opposite of the above is.
-
Empty: sentence??
Let’s see how to use it:
bool aaa; aaa = aaa ?? false; Copy the code
-
Cascade:..
This is essentially a chained call, as we wrote in the previous article, when the example was StringBuffer:
StringBuffer stringBuffer = StringBuffer(a); stringBuffer.. write("sss").. write("ssss"); Copy the code
So much for operators, good command of operators in writing code will get twice the result with half the effort, I hope you can master.
Flow control statement
This, by the way, is the basic foundation. Dart’s flow control statements are basically the same as Java’s. You can just use them.
If, for, while, brake, continue, switch, case, no more. This is Dart’s process control statement, exactly the same. Skip.
abnormal
Dart provides the Exception and Error types, as well as several subtypes. You can also define your own exception types. However, the Dart code can throw any non-NULL object as an Exception, not just an object that implements an Exception or Error.
Here is Exception in Dart:
The following image is Error in Dart:
An exception is thrown
-
As written in Java, all Dart exceptions are non-checked exceptions. Methods do not necessarily declare the exceptions they throw, and you do not require any exceptions to be caught.
// Throw an Exception object // throw new FormatException(' FormatException '); // Throw an Error object // throw new OutOfMemoryError(); Copy the code
-
The Dart code can throw any non-NULL object as an Exception, not just an object that implements an Exception or Error.
// Throw any non-null object // throw 'this is an exception '; Copy the code
Catch exceptions
-
All Dart exceptions are non-check exceptions. Methods do not necessarily declare the exceptions they throw, and you do not require any exceptions to be caught. You can declare a catch statement using either on or catch, or both. Use on to specify the exception type and catch to catch the exception object.
try { throw new OutOfMemoryError(); } on OutOfMemoryError { print('Out of memory'); } Copy the code
-
Catch () can take one or two arguments, the first of which is the exception object thrown and the second is the stack information (a StackTrace object).
try { throw new OutOfMemoryError(); } catch (e, s) { print('Exception details: $e'); print('Stack Trace: $s'); } finally { print('end'); } Copy the code
-
You can use a rethrow to rethrow the caught exception.
try { throw new OutOfMemoryError(); } catch (e, s) { print('Exception details: $e'); print('Stack Trace: $s'); rethrow; }Copy the code
Class dribs and drabs
The previous sections covered Dart variables, built-in types, functions (methods), operators, flow control statements, and exceptions. Now that you’ve learned a lot about the basic syntax of Dart, let’s take a look at Dart classes.
The constructor
A Java constructor is used to write a function (or method) :
class Point {
double x;
double y;
Point(int x, int y) {
this.x = x;
this.y = y; }}Copy the code
Here’s the recommended way to write in DART:
class Point {
num x;
num y;
Point(this.x, this.y);
}
Copy the code
Named constructor
Use named constructors to implement multiple constructors for a class, or use named constructors to make your intentions clearer.
class Point {
num x;
num y;
Point(this.x, this.y);
// Name the constructor
Point.fromJson(Map json) {
x = json['x'];
y = json['y']; }}Copy the code
Redirect constructor
A redirection constructor has no code. After the constructor is declared, other constructors are called with colons.
class Point {
num x;
num y;
Point(this.x, this.y);
// Redirect the constructor to call other constructors with colons
Point.alongXAxis(num x) : this(x, 0);
}
Copy the code
Initialization list
Instance parameters can be initialized before the constructor body is executed. Initialize expressions using commas. Initializer lists are great for setting the values of final variables.
import 'dart:math';
class Point {
// Final variables cannot be modified and must be initialized by constructors
final num x;
final num y;
final num distanceFromOrigin;
// Initialize the list
Point(x, y)
: x = x,
y = y,
distanceFromOrigin = sqrt(x * x + y * y);
}
Copy the code
Call the superclass constructor
Start by creating a superclass (superclass) from which the following code inherits:
class Parent {
int x;
int y;
// The superclass named constructor is not passed
Parent.fromJson(x, y)
: x = x,
y = y {
print('Superclass named constructor'); }}Copy the code
-
The superclass named constructor is not passed, and if you want to create a subclass using a named constructor defined in the superclass, you must implement the constructor in the subclass.
class Child extends Parent { int x; int y; Child.fromJson(x, y) : x = x, y = y, print('Subclass name constructor'); }}Copy the code
-
If the superclass does not have a default constructor, then you need to manually call other constructors of the superclass. Arguments to the superclass constructor cannot access this.
class Child extends Parent { int x; int y; // If the superclass does not have a default constructor, you need to manually call other superclass constructors Child(x, y) : super.fromJson(x, y) { // Arguments calling the parent constructor cannot access this print('Subclass constructor'); }}Copy the code
-
To use super() in the constructor initializer list, you need to put it last.
class Child extends Parent { int x; int y; Child.fromJson(x, y) : x = x, y = y, super.fromJson(x, y) { print('Subclass name constructor'); }}Copy the code
Constant constructor
Defining a const constructor ensures that all instance variables are final. The const keyword precedes the constructor name.
class Point2 {
// Defining the const constructor ensures that all instance variables are final
final num x;
final num y;
static final Point2 origin = const Point2(0.0);
// The const keyword precedes the constructor name and cannot have a function body
const Point2(this.x, this.y);
}
Copy the code
Factory constructor (singleton in Dart)
A factory constructor is a constructor that, unlike a normal constructor, does not automatically generate instances. Instead, the code determines which instance object to return. If a constructor does not always return a new object (singleton), use factory to define the constructor. The factory constructor cannot access this.
class Singleton {
String name;
// The factory constructor cannot access this, so static is used here
static Singleton _cache;
// Factory method constructor, keyword factory
factory Singleton([String name = 'singleton']) => Singleton._cache ?? = Singleton._newObject(name);// Define a named constructor to produce the instance
Singleton._newObject(this.name);
}
Copy the code
Setter and Getter
The GET and SET methods can be generated directly in Java and do not need to be defined in Dart. Each instance variable implicitly has a getter, and a setter if the variable is not final. You can create new properties by implementing getters and setters, which are defined using the GET and set keywords. You can start with instance variables, and then you can wrap them around functions without changing where your code is called. Here is an example of the code:
class Rectangle {
num left;
num top;
num width;
num height;
Rectangle(this.left, this.top, this.width, this.height);
num get right => left + width;
set right(num value) => left = value - width;
num get bottom => top + height;
set bottom(num value) => top = value - height;
}
Copy the code
Abstract Classes (Interfaces)
-
Cannot be instantiated unless a factory constructor is defined.
This is easy to understand; abstract classes in Java are also not instantiable.
-
Abstract classes are often used to define interfaces, as well as partial implementations.
Dart does not have the interface keyword, only abstract, so you can use abstract to generate interfaces:
abstract class Demo{ void zhujiang(); } class Zhu implements Demo{ @override void zhujiang() {} } Copy the code
-
Abstract classes usually have abstract methods that do not require keywords and end with a semicolon.
The above code can also be used for this example, just change implements to extends:
class Zhu extends Demo{ @override void zhujiang() {} } Copy the code
-
In interface mode, you need to override the member variables and methods of the abstract class, including private ones.
-
A class can implement a common class. Dart any class is an interface.
-
A class can implement multiple interfaces.
Implement just implements the interface, and you need to override the methods in the interface, otherwise they won’t be implemented. Another point is that you need to use the with keyword if you want to extents multiple classes. Said so much is not as good as directly look at the code, look at the code should be easier to understand some:
abstract class Demo{
void zhujiang();
}
abstract class Demo2{
void zhujiang();
}
abstract class Demo3{
void zhujiang();
}
class Zhu extends Demo with Demo2.Demo3 implements Demo3.Demo2{
@override
void zhujiang() {}
}
Copy the code
Can be called class
Implementing the call() method allows classes to be called just like functions. This is very simple, directly on the code:
class ClassFunction {
call(String a, String b, String c) => '$a $b $c! ';
}
main() {
var cf = new ClassFunction();
var out = cf("aaa"."flutter"."damon");
print('$out');
print(cf.runtimeType);
print(out.runtimeType);
print(cf is Function);
}
Copy the code
Here is the print:
lib/5.dart: Warning: Interpreting this as package URI, 'package:darttest/5.dart'.
aaa flutter damon!
ClassFunction
String
false
Copy the code
Mixin
- If A subclass does not override A method of superclass A, if two or more superclasses have A method of the same signature, the subclass takes the method of A of the last superclass that it inherits.
- If A subclass overrides its own A method, its own A method prevails.
I will not explain Minxin much here, but my understanding is similar to the policy pattern, which is to extract unchangeable interfaces and implement them more. I won’t write it here, but I’ll write an article about Minxin in Dart if possible.
The Dart generic
- Generics information in Java is compile-time; generics information does not exist at run time
- Dart’s generic types are hardwired and determinable at run time
var names = List<String> ();print(names is List<String>);//true
print(names.runtimeType); // List<String>
Copy the code
In Java, you can test if an object is a List, but you cannot test if it is a List. But in Dart it is precompiled.
Other uses of generics are similar to those in Java, so I won’t go over them here.
The Dart in the library
Dart has syntax that you don’t know, but it’s very useful. Go!
Libraries – Use core libraries
Use the import keyword to load the library:
import "dart:math";
void main() {
print(sqrt(4));// Square 2.0
}
Copy the code
For built-in libraries, the URIs use the special DART: scheme. For other libraries, you can use file system paths or package: scheme.
Libraries – Load third-party libraries
To use third-party libraries in Flutter, add dependencies to dependencies in Pubspec. yaml:
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^0.1. 0
dio: ^2.1. 0
Copy the code
Click the Packages Get in the upper right to import dependencies after adding them. Here is the three-way cry call method:
import "package:dio/dio.dart";
void main() {
getHttp();
}
void getHttp() async {
try {
Response response = await Dio().get("https://www.baidu.com");
print(response);
} catch (e) {
print(e); }}Copy the code
Here’s a website you can search for when you need to find third-party libraries: pub.dev/
Library – Specifies the library prefix
In Java coding, it is common for a class to call a method with the same name in two classes. In this case, fully qualified names are required, but not required in Dart:
import 'MyLib1.dart' as lib1;
import 'MyLib2.dart' as lib2;
void main() {
var myLib = lib1.MyLib();
var myLib2 = lib2.MyLib();
}
Copy the code
Dart and mylib1. dart both have a class named MyLib in the code above.
Library – Selective loading
- Show – loads only certain parts of the repository
- Hide – Filters out parts of the library
import 'Mylib1.dart' as lib1 show Test;
import 'Mylib2.dart' as lib2 hide Test;
var test = lib1.Test();
var lib = lib2.MyLib();
Copy the code
If you are using only part of the library’s functionality, you can choose what you want to import.
Library – Delayed loading
- Use deferred As import
- Call loadLibrary() with the identifier to load the library
import 'MyLib1.dart' deferred as lazyLib;
void main() {
lazyLoad();
}
lazyLoad() async {
await lazyLib.loadLibrary();
var t = lazyLib.Test();
t.test();
}
Copy the code
Use the await keyword to suspend code execution until the library is loaded. Can improve the program start speed. Packages for infrequently used features and long load times.
Libraries – Custom libraries
-
Start with a file as library:
library mylib; part 'util.dart'; part 'tool.dart'; void printMyLib() => print('mylib'); Copy the code
-
You then use part to split a library into multiple Dart files.
part of mylib; void printTool() => print('tool'); Copy the code
part of mylib; void printUtil() => print('util'); Copy the code
-
Imports do not fully share scope, while parts do. If library A imports library B and library B imports library C, there is no way for library A to directly use objects from library C. If B and C are parts of A, they share all objects. And includes all imports.
import 'mylib/mylib.dart'; void main() { printMyLib(); printUtil(); printTool(); } Copy the code
conclusion
This article before writing for a long time, originally thought each section is divided into an article published, so there will be several articles π, but again thought that is not too kind, directly write the whole hair. See digging gold is the big guy, all kinds of front-line factory technology, all kinds of Ali Tencent name of the article… Can not than can not, just a small broken company has been trying to advance the small code farmers, write the article may not be very good, but also calculate the heart, I hope you can like, finally say a sentence, don’t forget to like the comments πππ, grateful.