1. Dart syntax
1. Development tools
Vscode, install plug-ins: dart, Code Runner
2. Entry method
main(){ print('你好,dart'); } // 表示main方法没有返回值 void main(){ print('你好,dart'); }
3 .Dart variables
Dart is a powerful scripting language that does not need to predefine types and will automatically infer types
Variables defined in dart can be declared through the var keyword
There is type checking in dart
Such as:
var str = 'this is var'; String str = 'this is string'; int str = 123;
4. Dart variables
Final const can define constants
Final can be started without assignment , can only be assigned once; and final not only has the characteristics of const compile-time constants, but the most important thing is that it is a run-time constant, and final is lazy initialization, that is, it is initialized before the first use at run-time
Such as:
const NUM = 123; final Time = new DateTime.now();
5.Dart data type
Numbers: int double
Strings: String
如:var str = 'this is a string'; String str = 'this is a string'; // 定义多行字符串 String str = ''' my name is wq; my age is 23; '''; // 字符串拼接 String name = 'wq'; int age = 23; String myInfo = '我的名字叫$name,我今年$age岁'; // 注意:如果使用+实现字符串拼接,那么必须要是同类型的数据 String firstName = '王'; String lastName = '清'; String myInfo = lastName + ':' + firstName;
Booleans( Boolean): bool
bool flag = true;
List (list): It is an array in js
// 第一种定义List的方式 var list1 = [1,2,3]; print(list1.length); // 第二种定义List的方式 var list = new List(); list.add(1); list.add(2); // 定义List指定元素类型 var list = new List<String>(); list.add('王清');
Maps (dictionary): Map is an object related to key-value pairs
// 第一种定义Map var person = { "name": "王清", "age": 23 }; print(person['name']); // 第二种定义Map var p = new Map(); p['name'] = '王清'; print(p); 问:如何判断类型?(关键字 is) var str = '123'; if (str is String) { print('字符串类型'); } else if (str is int) { print('数值类型'); } 注意: 取整运算符 如:print(12~/5); // 2 为空赋值 如:int b; b??=23; print(b); // 23 解释:如果b为空的话就赋值23 int a; int b = a??10; print(b); // 10
6 .Type conversion
1) Conversion between Number and String types
①Number is converted to String type toString()
int num = 12; print(num.toString());
②String is converted to Number type parse
String str = '123'; print(int.parse(str)); print(double.parse(str));
2) Convert other types to Booleans type
①isEmpty:判断当前字符串是否为空 String str = ''; print(str.isEmpty); ②未赋值 var myNum; print(myNum == null); // true ③为0 var myNum=0; print(myNum ==0); // true ④为NaN var myNum = 0/0; print(myNum.isNaN); // true
7.List
Common attributes:
length: length
reversed: flip
var list = [1,2,3];
print(list.reversed.toList());
isEmpty: whether it is empty
isNotEmpty : Whether it is not empty
Commonly used methods:
add(): Add an element, only one element can be added
addAll(): Splice the list list.addAll([ 1,2,3])
indexOf(): Search the data, find the subscript of the returned element, if not found,
’s- ## removeAt(): Delete the element with the specified index value fillRange(): Modify the specified range element to a new element list.fillRange(2, 4, 1); // Modify the subscript 2~3 The elements between are 1 insert(index,value): Insert element at the specified subscript insertAll(index,list): Insert the list at the specified subscript list.insertAll(2 , [100,1]); toList(): Convert other types to lists join(): Convert List to string String strList = list.join('-'); split(): Convert the string into List8.Set Set is an unordered and non-repeating set, so data cannot be obtained through subscripts; it The most important function is to remove duplicates from the list Commonly used attributes: isEmpty: whether it is empty isNotEmpty: whether it is not empty first: returns the first An element last: return the last element length: length Common methods: addAll: add list and convert to Set contains: Query whether it contains a single element set.contains(1) containsAll: Query whether it contains multiple elements set.containsAll([1,2]) difference: Return two set different elements set1.difference(set2).toList() intersection: Return two elements with the same elements union: Contains all elements of the two setsSet set1 = [1,2,3].toSet(); Set set2 = [2,3,4].toSet(); print(set1.union(set2).toList()); // [1,2,3,4]
Set set1 = [1,2,100,200,300,3].toSet(); var list = set1.firstWhere((value){ return value > 100; }); print(list); // 200
Set set1 = [1,2,100,200,300,3].toSet(); var list = set1.firstWhere((value){ return value > 100; }); print(list); // 300
Set set1 = [1,2,100,200,300,3].toSet(); set1.removeWhere((value){ return value > 100; }); print(set1); // {1, 2, 100, 3}
Set set1 = [1,2,100,200,300,3].toSet(); set1.retainWhere((value){ return value > 100; }); print(set1); // {200,300}
Set set1 = [1,2,100,200,300,3].toSet(); set1.retainAll([1,2]); print(set1); // {1,2}
Set set1 = [1,2,100,200,300,3].toSet(); set1.removeAll([1,2]); print(set1); // {100,200,300,3}
// 方法一 List list = [1,2,3,4,1,2]; Set s = new Set(); s.addAll(list); print(s.toList()); // 方法二 List list = [1,2,3,4,1,2]; print(list.toSet().toList());
##
};
# :Whether the key-value pair of the value exists in the Map
. # For example: m.containsKey("name")
10. forEach map where any every (common to List, Set, Map)
General loop:
List list = [100,200,300,400];
for(var i in list){
print(i); // 100 200 300 400
}
forEach loop :
List list = [100,200,300,400];
list.forEach((value) => print(value));
list.forEach((value){
PRINT (VALUE); // 100 200 300 400
});
Map Cycle:
## This list list = [100,200,300,400]; var newList = list.map((value){ return value * 2; }); // [200,400,600,800] where loop: List list = [100,200,300,400]; var newList = list.where((value){ return value > 200; }); print(newList.toList()); // [300,400] any loop: Meaning: Determine whether there are elements that meet the conditions. If there are elements, return true List list = [100,200,300,400]; Var flag = list.any((value){ return value > 200; }); print(flag); every loop: Meaning: Determine whether all elements meet the conditions, Returns true if all elements match List list = [100,200,300,400]; var flag = list.every((value){ return value > 0; }); Print(flag); // true11. Functions, parameters, closures, etc. 1) Basic function format Return type method name (parameter 1, parameter 2...){ Method body return return value; } ① Define the parameter type as int. If it is other types, an error will be reported. getNum (60); if (Age! = NULL && SEX! = NULL) { Return '$ Name $ Age $ Sex'; return '$name'; }print(printUserInfo('Wang Qing', 20)); # . }
#}
# Print (Printuserinfo ('Wang Qing'));
## ④ Naming parameters # String PRINTUSERINFO (String name, {string sex, int age=10}){ ## return '$name';## ⑤ Anonymous method
Function fn = () {
Return 'I am an anonymous function'
};
## PRINT (fn()); ⑥Arrow function: Note that arrow functions do not support multi-line statements list.forEach((value)=>print(value));#: Judging whether a value is even or a wonderful number? ISEVEN is it even # Isodd whether it is a wonderful number # ⑦ Self -executing function ((String Str) { PRint ( str); })('IIFE'); Variables will pollute the global Features of local variables: If they are not resident in memory, they will be recycled by the garbage collection mechanism and will not pollute the global Want to achieve the function: resident in memory, will not pollute the global12. Class objects Everything in Dart is an object, and all objects inherit from the Object class; Dart is an object-oriented language that uses classes and single inheritance. All objects are instances of classes, and all classes are subclasses of Object Such as: class Person{ String name;Int Age; // Construction function Person (String name, int age) { This.name = name;
## This.age.age = age;
. int age){
this.name = name; this.age =
Person (this.name, this.age);
void getinfo () {
PRINT ("$ {this.name} --- $ {this. age}");
##’’; p.getInfo(); Person p2 = new Person.now('Wang Sicong', 30);
p2.getInfo(); Class
2. Quote
import 'person.dart';
void main () {
Person P = New Person.now (' Wang Qing',23);
p.getInfo(); There are no access modifiers such as private, public, and protected
But we can use _ to define a property or method as private
Private properties or methods cannot be instantiated and called directly, and can only be called internally New methods or properties to use
The function can be abbreviated as follows
Person(this._name,this.age);
// Named constructor
Person.now(String name,int age) {
this. print ("${this._name}---${this.age}");
Extracted into a file
1) Getter and setter modifiers in the class:
class Rect{
num height;
num width;
Rect(this.height,this.width);
set areaWidth(value){
this.height = value;
}
get area{
using using ’ s through ’s through ’s through ’s out through through through through through through‐ over through through over‐‐to‐‐‐‐‐‐ trail to return this.height * this.width;
# Rect r = new Rect(10, 10);
// Call the get modified method by accessing the property
Print(r.area);
// Call set to assign a value to the property by assigning a value
r.areaWidth = 20;
print(r.area); 2) In Dart, instance variables can be initialized before the constructor body is run. class Rect{
num height;
num width;
Rect() ;
} ’ ’s ’ s ’ ‐ ‐ ‐ void main(){ Rect r = new Rect();## 3) Static members
①Use the static keyword to implement class-level variables and functions
②Static methods cannot access non-static members, and non-static methods can access static members
Class Person {
Static String name = 'Wang Qing';
static void show () {
# PRINT (name);
}
##} void Main # Person.show(); 4) Object operators in Dart: ? Conditional operator as Type conversion is type judgment ..Cascading operation Such as: num age; Person(this.name,this.age); this.age}'); Person p; Whether p is empty, if it is empty, the method or attribute will not be executed. Whether the object is an instantiation of the class if (p is Person) { . var p1; p1 =''; (p1 as Person).show(); ...show ();
##} 5) Inheritance ① Use extends keywords to inherit the parent class # ② The class will inherit the visible attributes and methods in the parent class, but will not inherit the constructor ③ The subclass can override the parent class’s method getter and setter Such as: class Person { String name; num age; -- String height = '170cm'; num age; ; Person.other(this.name,this.age); void printInfo(){ ‐ ‐ use using use through ’ s ’ s through ’ s ‐ ‐ ‐ ‐ ft t ‐ to this.age}'); this.age}');# class Web extends Person{
String sex;
this.sex = sex; # void run(){
PRINT ('Running');
##} Void Work () { // The method of calling the parent class through super class super.work();'PRINTINFO');
##} } void Main () { Web w = new web ('Zhang San', 12.'Male');# Abstract classes in Dart: Dart abstract classes are mainly used to define standards. Subclasses can inherit abstract classes or implement abstract class interfaces
①Abstract classes are defined through the abstract keyword
② The abstract method in Dart cannot be declared by Abstract. There is no method of method in Dart. The abstract class should be achieved as the interface implementation. All methods and attributes are defined in the abstract class
# ⑤ The abstract class cannot be instantiated. Difference:
① If you want to repeat the method in the abstract class, and use the abstract method to restrain the self -class painting, we use Extends to inherit the abstract class
② For standard purposes, we use implements to implement the abstract class
Abstract class:
Abstract class Animal{
void eat(); // Abstract method
void drink(){
print('I want to drink water'); # void eat(){ void eat() @override
void drink () {
# PRINT ('Drinking water');
}
void run () {
## Let's run~'); #D.drink (); // If you use the Animal class definition, you cannot call your own method in the DOG class Animal a = New Dog ();## // a.run(); Error
}
’ ’s Error's ’ ‐ ‐ ‐ ‐ using using to ‐ to have
abstract class DB{
String URL; class MySQL implements DB{
’ ’s ’ s ’ through ’ s ’ ’ way through ‐ ‐ ‐ ‐ ‐ ‐ ‐ to Return null;
# } void main () {} A class to implement multiple interfaces: Abstract class a { PRINTA ();
} abstract class B{ printB(); @override printA() return null; printB() { return null;
# Conditions for using mixins:
① Classes as mixins can only inherit from Object and cannot inherit from other classes
② Classes as mixins cannot have constructors
③A class can mixins multiple mixins classes
④Mixins are neither inheritance nor interfaces, but a brand-new feature
Such as:
class A{
void printA(){
print('A'); #Void Printb () {
# Print ('B');
}
##}## Class C Extends A with b {
# }
class D with A,B{
}
’’s ’ through ’ through ’'s ’ through ’ through ’ s ’ through ’' ‐ ‐ ‐ ‐ ‐ ‐ void main(){
C c = new C();
c.
# d.printB(); } Note: Whether it is extends or with, if the same method exists, whoever is behind will call it 14. Generics Understanding: Generics solve the reusability of classes, interfaces, and methods and support for unspecific data types (type checking) ①Generic methods T getData List list = new List
void add(T value){
this.list.add(value);
}
}
void main(){
MyArray myArray = new MyArray
myArray.add('wq');
}
③泛型接口
abstract class Cache
getByKey(String key);
void setBykey(String key,T value);
}
class FileCache
@override
getByKey(String key) {
return null;
}
@override
void setBykey(String key, T value) {
print('$key --- $value');
}
}
void main(){
FileCache fc = new FileCache
fc.setBykey('wq', '我是文件缓存');
}
15.Dart中的库
①我们自定义的库
import 'lib/XXX.dart';
②系统内置库
import 'dart:io';
import 'dart:convert';
void main() async{
var result = await getDataFromZhihuAPI();
print(result);
}
//api接口: http://news-at.zhihu.com/api/3/stories/latest
getDataFromZhihuAPI() async{
//1、创建HttpClient对象
var httpClient = new HttpClient();
//2、创建Uri对象
var uri = new Uri.http('news-at.zhihu.com','/api/3/stories/latest');
//3、发起请求,等待请求
var request = await httpClient.getUrl(uri);
//4、关闭请求,等待响应
var response = await request.close();
//5、解码响应的内容
return await response.transform(utf8.decoder).join();
}
③Pub管理系统中的库
第一步:从下面网址找到要用的库
https://pub.dev/packages
https://pub.flutter-io.cn/packages
https://pub.dartlang.org/flutter/
第二步: 创建一个pubspec.yaml文件,内容如下:
name: xxx
description: A new flutter module project.
dependencies:
http: ^0.12.1
第四步:在文件所在目录执行 pub get
第五步:写代码
import 'package:http/http.dart' as http;
import 'dart:convert' as convert;
void getData() async {
var url = 'http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1';
var response = await http.get(url);
if (response.statusCode == 200) {
print(convert.jsonDecode(response.body));
# # void main() import Import 'lib/mymath.dart' show getname; // Only introduce the getname method steot 'lib/mymath.dart' hide getname; // Only hide the getname method #② delay loading (deferred as) also becomes lazy load. You can load when needed to reduce the launch time of the app Import 'xxx .dart' deferred asThe above is the detailed content of Summary of Dart basic knowledge points. For more information, please follow other related articles on the PHP Chinese website!