亚洲成A人片在线观看网站_成年网站免费视频A在线双飞_日日日日做夜夜夜夜无码_久久夜色撩人精品国产小说

Dart 備忘清單

包含最(zui)重要概念、功能、方(fang)法等的(de) 備(bei)忘單。初學(xue)者的(de)完(wan)整(zheng)快速參考

入門

安裝 Dart

Windows

C:\> choco install dart-sdk # Windows

Linux

執行以下一次性設置

$ sudo apt-get update
$ sudo apt-get install apt-transport-https
$ wget -qO- //dl-ssl.google.com/linux/linux_signing_key.pub | sudo gpg --dearmor -o /usr/share/keyrings/dart.gpg
$ echo 'deb [signed-by=/usr/share/keyrings/dart.gpg arch=amd64] //storage.googleapis.com/download.dartlang.org/linux/debian stable main' | sudo tee /etc/apt/sources.list.d/dart_stable.list

安(an)裝 Dart SDK

$ sudo apt-get update
$ sudo apt-get install dart

Mac

$ brew tap dart-lang/dart
$ brew install dart

hello.dart

// 應(ying)用執行開始(shi)的頂級(ji)函數
void main() {
    print("Hello World!"); // 打(da)印到控(kong)制(zhi)臺(tai)
}

每個應用程序都有一個 main() 函數

Windows

$ dart compile exe hellow.dart
$ time ./hello.exe
Hello World!

變量

int x = 2; // 顯式鍵(jian)入
var p = 5; // 類型(xing)(xing)推斷 - 具有類型(xing)(xing)推斷的通用var
dynamic z = 8; // 變量可以(yi)采用任何類型(xing)
z = "cool"; // cool

// 如果您從不(bu)打算(suan)更(geng)改變量,請使用 final 或 const
// 像這樣的東西(xi):
final email = "temid@gmail.com";
// 與 var 相(xiang)同,但不能(neng)重(zhong)新分配
final String email = "temid@gmail.com";
// 你不能改變(bian)價值
const qty = 5; // 編譯時常數(shu)

數據類型

// 整數,范圍(wei) -2^63 到 2^63 - 1
int age = 20;
// 浮點數(shu)字

double height = 1.85;
// 您還可以(yi)將變量聲(sheng)明(ming)為 num
// x 可(ke)以(yi)同時(shi)具有 int 和(he) double 值
num x = 1;
num += 2.5;
print(num); // 打印: 3.5

String name = "Nicola";
bool isFavourite = true;
bool isLoaded = false;

注釋

// 這是一條正常(chang)的(de)單行注釋
/// 這是一個文(wen)檔注(zhu)釋,用于(yu)文(wen)檔庫,
/// 類(lei)及其(qi)成(cheng)員。 IDE 和 dartdoc 等工具(ju)
/// doc 特(te)別注釋。
/* 也支持此類注釋(shi) */

字符串插值

// 可(ke)以對(dui)字符串(chuan)類型使用單引號或(huo)雙引號
var firstName = 'Nicola';
var lastName = "Tesla";
// 可以用 $ 將變量嵌(qian)入到(dao)字符串(chuan)中
String fullName = "$firstName $lastName";
// 與 + 連接
var name = "Albert " + "Einstein";
String upperCase = '${firstName.toUpperCase()}';
print(upperCase); // 打印(yin): NICOLA

導入 Imports

// 導入(ru)核心庫(ku)
import 'dart:math';
// 從外部包導入庫
import 'package:test/test.dart';
// 導入文件
import 'path/to/my_other_file.dart';

操作符

算術運算符

print(2 + 3);  // 打印: 5
print(2 - 3);  // 打印(yin): -1
print(2 * 3);  // 打印: 6
print(5 / 2);  // 打印: 2.5 - 結果是 double
print(5 ~/ 2); // 打印(yin): 2 - 結果(guo)是n int
print(5 % 2);  // 打印: 1 - 余
int a = 1, b;

// 增
b = ++a; // 前(qian)增(zeng)量 - 在(zai) b 獲得(de)其值之前(qian)增(zeng)加 a
b = a++; // 后(hou)(hou)增量 - 在 b 獲得它的值之后(hou)(hou)增加 a
// 遞(di)
b = --a; // 前(qian)減量(liang) - 在(zai) b 獲得它的(de)值之前(qian)減少 a
b = a--; // 后減(jian)量 - 在 b 獲得它的值之后遞減(jian) a

邏輯運算符

// !expr 反(fan)轉(zhuan)表(biao)達式(將 false 更改為 true,反(fan)之(zhi)亦然)
// ||  邏輯或
// &&  邏輯與
bool isOutOfStock = false;
int quantity = 3;
if (!isOutOfStock && (quantity == 2 || quantity == 3)) {
  // ...Order the product...
}

等式和關系運算符

print(2 == 2); // 打(da)印: true - 平等(deng)的
print(2 != 3); // 打印(yin): true - 不相等(deng)
print(3 > 2);  // 打(da)印: true - 比...更棒
print(2 < 3);  // 打印: true - 少于
print(3 >= 3); // 打印: true - 大于或等于
print(2 <= 3); // 打印: true - 小于或等于

控制流:條件

if 和 else if

if(age < 18){
    print("Teen");
} else if( age > 18 && age <60){
    print("Adult");
} else {
    print("Old");
}

switch case

enum Pet {dog, cat}
Pet myPet = Pet.dog;
switch(myPet){
    case Pet.dog:
        print('My Pet is Dog.');
        break;
    case Pet.cat:
        print('My Pet is Cat.');
        break;
    default:
        print('I don\'t have a Pet');
}
// 打印(yin): My Pet is Dog.

控制流:循環

while 循環

while (!dreamsAchieved) {
  workHard();
}

循環迭代之前的 while 循環檢查條件

do-while 循環

do {
  workHard();
} while (!dreamsAchieved);

do-while 循環(huan)在(zai)執行循環(huan)內(nei)的語句后(hou)驗證條件

for 循環

for(int i=0; i< 10; i++){
    print(i);
}
var numbers = [1,2,3];
// 列表的 for-in 循環
for(var number in numbers){
    print(number);
}

Collections

Lists

// 有序的(de)對象組
var list = [1, 2, 3];
print(list.length); //Print: 3
print(list[1]); //Print: 2
// 列表聲(sheng)明和初始(shi)化的其他方(fang)式
List<String> cities = <String>["New York", "Mumbai", "Tokyo"];
// 創建一個(ge)編譯時常量的列表(biao)
const constantCities = const ["New York", "Mumbai", "Tokyo"];

Maps

// 映射是關聯鍵和值的對象
var person = Map<String, String>();
// 要初始化地(di)圖,請執行以下操作:
person['firstName'] = 'Nicola';
person['lastName'] = 'Tesla';
print(person);
// 打(da)印: {firstName:Nicola, lastName:Tesla}
print(person['lastName']);
// 打印: Tesla

var nobleGases = {
  // Key: Value
  2: 'helium',
  10: 'neon',
  18: 'argon',
};

Sets

// Dart 中的(de)集合是唯(wei)一項的(de)無序集合
var halogens = {'fluorine', 'chlorine', 'bromine', 'iodine', 'astatine'};
// 創建一個空集
var names = <String>{};
Set<String> names = {}; // 這也有(you)效
//var names = {}; // 創(chuang)建地圖,而(er)不是集合(he)

函數

函數示例

// dart 中的(de)函數是(shi)對象(xiang)并且有一個類(lei)型(xing)
int add(int a, int b){
    return a+b;
}
// 函數可以(yi)分配給變量
int sum = add(2,3); // 回報(bao):5
// 可以作(zuo)為參數傳遞給其(qi)他函數
int totalSum = add(2, add(2,3)); // 返回:7

箭頭語法 (=>)

// 只包含一個表(biao)達(da)式的(de)函數,您可以(yi)使用簡寫語法(fa)
bool isFav(Product product) => favProductsList.contains(product);

Anonymous (lambda) functions

// 沒有(you)名(ming)字(zi)的小單行函(han)數(shu)
int add(a,b) => a+b;
// lambda 函(han)數大多作為(wei)參(can)數傳遞給其(qi)他函(han)數
const list = [
  'apples', 'bananas', 'oranges'
];

list.forEach(
  (item) =>
    print('${list.indexOf(item)}: $item')
);
// 打(da)印: 0: apples 1: bananas 2: oranges

類和對象

類 Class

class Cat {
    String name;
    // 方法(fa)
    void voice(){
        print("Meow");
    }
}

對象 Object

// 類的實例
// 在 myCat 下面是 Cat 類(lei)的(de)對象(xiang)
void main(){
    Cat myCat = Cat();
    myCat.name = "Kitty";
    myCat.voice(); // 打印: Meow
}

構造函數

class Cat {
    String name;
    Cat(this.name);
}
void main(){
    Cat myCat = Cat("Kitty");
    print(myCat.name); // 打印: Kitty
}

抽象類

// 抽象類——不能(neng)實例(li)化的(de)類
// 這個類被聲(sheng)明為抽象的,因此不能(neng)被實例化
abstract class AbstractContainer {
  // 定義(yi)構造(zao)函數(shu)、字段、方法...
  void updateChildren(); // 抽象(xiang)方法
}

Getters Setters

// 提供(gong)對(dui)對(dui)象(xiang)屬性的讀(du)寫(xie)訪問
class Cat {
    String name;
    // getter
    String get catName {
        return name;
    }
    // setter
    void set catName(String name){
        this.name = name;
    }
}

隱式接口

一個基本的界面

// 一(yi)個人。隱式接口包(bao)含 greet()。
class Person {
  // 在接口中,但(dan)僅在此庫中可見。
  final String _name;
  // 不(bu)在接(jie)口中,因為這是一(yi)個構造(zao)函數。
  Person(this._name);
  // 在接(jie)口中
  String greet(String who) => 'Hello, $who. I am $_name.';
}
// Person 接口(kou)的(de)實現。
class Impostor implements Person {
  String get _name => '';
  String greet(String who) => 'Hi $who. Do you know who I am?';
}
String greetBob(Person person) => person.greet('Bob');
void main() {
  print(greetBob(Person('Kathy')));
  // 打(da)印: Hello, Bob. I am Kathy.
  print(greetBob(Impostor()));
  // 打(da)印: Hi Bob. Do you know who I am?
}

擴展類

class Phone {
    void use(){
        _call();
        _sendMessage();
    }
}
// 使用 extends 創建子類
class SmartPhone extends Phone {
    void use(){
        // 使用 super 來引用超類
        super.use();
        _takePhotos();
        _playGames();
    }
}

枚舉

定義枚舉

enum Color { red, green, blue }

使用枚舉(ju),像訪(fang)問(wen)任何其他(ta)靜(jing)態變量一樣(yang)訪(fang)問(wen)枚舉(ju)值:

final favoriteColor = Color.blue;
if (favoriteColor == Color.blue) {
  print('Your favorite color is blue!');
}

枚舉中(zhong)的(de)(de)每個(ge)值(zhi)都有一個(ge)索引獲取器,它返(fan)回(hui)枚舉聲明中(zhong)值(zhi)從零開始(shi)的(de)(de)位置。 例如(ru),第(di)一個(ge)值(zhi)的(de)(de)索引為 0,第(di)二(er)個(ge)值(zhi)的(de)(de)索引為 1

assert(Color.red.index == 0);
assert(Color.green.index == 1);
assert(Color.blue.index == 2);

要(yao)獲取(qu)所有(you)枚舉值的列表,請使用枚舉的值常(chang)量(liang)

List<Color> colors = Color.values;
assert(colors[2] == Color.blue);

您可(ke)以在 switch 語(yu)句中使用枚舉,如果您沒有(you)處理枚舉的所有(you)值,您將收(shou)到警告(gao):

var aColor = Color.blue;

switch (aColor) {
  case Color.red:
    print('Red as roses!');
    break;
  case Color.green:
    print('Green as grass!');
    break;
  default: // 沒有這(zhe)個,你(ni)會看到(dao)一(yi)個警告
    print(aColor); // 'Color.blue'
}

如果您需要訪問枚舉值的名稱,例如 Color.blue 中的“blue”,請使用 .name 屬性:

print(Color.blue.name); // 'blue'

枚舉示例

聲明了一個具有多個實例、實例變量、一個 getter 和一(yi)個已實現接口(kou)的增強型(xing)枚舉

// 簡單定義一個枚舉(ju)類型(xing)
enum PlanetType { terrestrial, gas, ice }

// 定義一個行星復雜的枚舉類型
enum Planet {
  mercury(planetType: PlanetType.terrestrial, moons: 0, hasRings: false),
  venus(planetType: PlanetType.terrestrial, moons: 0, hasRings: false),
  
  uranus(planetType: PlanetType.ice, moons: 27, hasRings: true),
  neptune(planetType: PlanetType.ice, moons: 14, hasRings: true);

  // 定義一個構造函數(shu)
  const Planet({required this.planetType, required this.moons, required this.hasRings});

  // 聲(sheng)明枚舉(ju)類型中的變量
  final PlanetType planetType;
  final int moons;
  final bool hasRings;

  // 實現枚(mei)舉類型中的(de)get 方(fang)法
  bool get isGiant =>
    planetType == PlanetType.gas || planetType == PlanetType.ice;
}

// 使用枚舉類型(xing)
void main()
{
  final yourPlanet = Planet.mercury;

  if (!yourPlanet.isGiant) {
    print('Your planet is not a "giant planet".');
  }
}

Mixin

定義Mixin

Dart中類只能單繼承,使用Mixin可(ke)以(yi)實現多個繼(ji)承,復(fu)用(yong)多個類中代碼(ma)的方(fang)法。

// 定義(yi)Mixin
mixin Piloted {
  int astronauts = 1;

  void describeCrew() {
    print('Number of astronauts: $astronauts');
  }
}

使用with關鍵字并在其后跟上Mixin類的名字來使用

// 使用with將(jiang)Piloted混入
class PilotedCraft extends Spacecraft with Piloted {
  // ···
}

支(zhi)持混入(ru)多(duo)個Mixin,如果出現(xian)相同的(de)方法(fa)后混入(ru)的(de)Mixin會覆蓋前(qian)面的(de)

class Musician extends Performer with Musical {
  // ···
}

// 混入(ru)多個Mixin
class Maestro extends Person with Musical, Aggressive, Demented {
  Maestro(String maestroName) {
    name = maestroName;
    canConduct = true;
  }
}

使用關鍵字on來指定哪些類可以使用該Mixin,比如有Mixin類MusicalPerformer,但是MusicalPerformer只能被Musician類使用,則可以這樣定義MusicalPerformer

class Musician {
  // ...
}
// 現(xian)在(zai)MusicalPerformer 只(zhi)能在(zai) Musican及其子類中使用(yong)
mixin MusicalPerformer on Musician {
  // ...
}
class SingerDancer extends Musician with MusicalPerformer {
  // ...
}

異常

Throw

// 拋出(chu) throws 或引發 raises 和異常 exception
throw IntegerDivisionByZeroException();
// 你也可以拋出任意對象
throw "Product out of stock!";

Catch

try {
    int c = 3/0;
    print(c);
} on IntegerDivisionByZeroException {
    // 一(yi)個(ge)特定(ding)的(de)異常
    print('Can not divide integer by 0.')
} on Exception catch (e) {
    // 任何(he)其他(ta)異常情(qing)況(kuang)
    print('Unknown exception: $e');
} catch (e) {
    // 沒有指(zhi)定類型(xing),處理所有
    print('Something really unknown: $e');
}

Finally

// 確保某些代碼無論是否拋出(chu)異常都能(neng)運行
try {
  cookFood();
} catch (e) {
  print('Error: $e'); // 先處理異常
} finally {
  cleanKitchen();     // 然(ran)后清理
}

Futures

Async Await

// 異步函(han)數:它們在設(she)置可能(neng)耗時(shi)的操作后返回(hui)
// async 和 await 關鍵字支持(chi)異步(bu)編程(cheng)
Future<String> login() {
  String userName="Temidjoy";
  return
    Future.delayed(
      Duration(seconds: 4), () => userName
    );
}
// 異步(bu)
main() async {
  print('Authenticating please wait...');
  print(await userName());
}

各種各樣的

Null 和 Null 感知

int x; // 任何對象的(de)初始值為 null
// ?? 空感知運(yun)算符(fu)
x ??=6;   // ??= 賦(fu)值運算符,僅當變量當前為 null 時才為其賦(fu)值
print(x); // 打印(yin): 6
x ??=3;
print(x); // 打印: 6 - 結果仍然是(shi) 6
print(null ?? 10); // 打印: 10。如果(guo)不為空,則(ze)顯示左(zuo)側(ce)的值,否則(ze)返(fan)回右側(ce)的值

三元運算符

// 條件(jian) ? 條件(jian)如(ru)果為真(zhen) : 條件(jian)如(ru)果為假(jia)
bool isAvailable;
isAvailable ? orderproduct() : addToFavourite();

條件屬性訪問

userObject?.userName
// 上面的代碼片段等效于以下代碼:
(userObject != null) ? userObject.userName : null
// 您(nin)可(ke)以將(jiang) ? 的多(duo)種用途鏈接起(qi)來。一起(qi)在一個表達式中
userObject?.userName?.toString()
// 如(ru)果 userObject 或(huo) userObject.userName 為 null,則前面的代碼(ma)返回 null 并且從不調用 toString()

級聯符號 (..)

// 允(yun)許(xu)您對同一(yi)對象進行一(yi)系列操作
// 而不是這樣做
var user = User();
user.name = "Nicola";
user.email = "nicola@g.c";
user.age = 24;
// 你可以這樣做
var user = User()
  ..name = "Nicola"
  ..email = "nicola@g.c"
  ..age = 24;

擴展運算符 (...)

// 將多(duo)個值插入(ru)到集合(he)中
var list = [1, 2, 3];
var list2 = [0, ...list];
print(list2.length); // 打印(yin): 4

另見

  • (dart.dev)