包含最重要概念、功能、方法等的 Dart 备忘单。初学者的完整快速参考
入门 安装 Dart
完整教程请参阅 Dart 中文社区 https://dart.cn/get-dart/
Windows 1 C:\> choco install dart-sdk
Linux 执行以下一次性设置
1 2 3 4 $ sudo apt-get update $ sudo apt-get install apt-transport-https $ wget -qO- https://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] https://storage.googleapis.com/download.dartlang.org/linux/debian stable main' | sudo tee /etc/apt/sources.list.d/dart_stable.list
安装 Dart SDK
1 2 $ sudo apt-get update $ sudo apt-get install dart
Mac 1 2 $ brew tap dart-lang/dart $ brew install dart
hello.dart 1 2 3 4 void main() { print ("Hello World!" ); }
每个应用程序都有一个 main()
函数
Windows 1 2 3 $ dart compile exe hellow.dart $ time ./hello.exe Hello World!
变量 1 2 3 4 5 6 7 8 9 10 11 12 int x = 2 ; var p = 5 ; dynamic z = 8 ; z = "cool" ; final email = "temid@gmail.com" ;final String email = "temid@gmail.com" ;const qty = 5 ;
数据类型 1 2 3 4 5 6 7 8 9 10 11 12 13 14 int age = 20 ;double height = 1.85 ;num x = 1 ;x += 2.5 ; print (x); String name = "Nicola" ;bool isFavourite = true ;bool isLoaded = false ;
注释
字符串插值 1 2 3 4 5 6 7 8 9 var firstName = 'Nicola' ;var lastName = "Tesla" ;String fullName = "$firstName $lastName " ;var name = "Albert " + "Einstein" ;String upperCase = '${firstName.toUpperCase()} ' ;print (upperCase);
导入 Imports 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 import 'dart:math' ;import 'package:test/test.dart' ;import 'path/to/my_other_file.dart' ;import 'package:lib/lib.dart' as lib;lib.Element element = lib.Element (); import 'package:lib1/lib1.dart' show foo;import 'package:lib2/lib2.dart' hide foo;import 'package:greetings/hello.dart' deferred as hello;
操作符 算术运算符 1 2 3 4 5 6 7 print (2 + 3 ); print (2 - 3 ); print (2 * 3 ); print (5 / 2 ); print (5 ~/ 2 ); print (5 % 2 ); int a = 1 , b;
1 2 3 4 5 6 b = ++a; b = a++; b = --a; b = a--;
逻辑运算符 1 2 3 4 5 6 7 8 bool isOutOfStock = false ;int quantity = 3 ;if (!isOutOfStock && (quantity == 2 || quantity == 3 )) { }
等式和关系运算符 1 2 3 4 5 6 print (2 == 2 ); print (2 != 3 ); print (3 > 2 ); print (2 < 3 ); print (3 >= 3 ); print (2 <= 3 );
运算符优先级示例 1 2 3 4 if ((n % i == 0 ) && (d % i == 0 )) ...if (n % i == 0 && d % i == 0 ) ...
位运算符和移位运算符
操作符
含义
&
与(AND)
|
或(OR)
^
异或(XOR)
~expr
一元位补码(0 变为 1;1 变为 0)
<<
左移
>>
右移
>>>
无符号右移
1 2 3 4 5 6 7 8 9 10 11 12 13 14 final value = 0x22 ;final bitmask = 0x0f ;assert ((value & bitmask) == 0x02 );assert ((value & ~bitmask) == 0x20 );assert ((value | bitmask) == 0x2f );assert ((value ^ bitmask) == 0x2d );assert ((value << 4 ) == 0x220 ); assert ((value >> 4 ) == 0x02 );
级联表示法 级联 (.., ?..) 允许您对同一对象进行一系列操作。除了访问实例成员之外,您还可以调用同一对象的实例方法。这通常可以节省您创建临时变量的步骤,并允许您编写更流畅的代码。考虑以下代码:
1 2 3 4 var paint = Paint() ..color = Colors.black ..strokeCap = StrokeCap.round ..strokeWidth = 5.0 ;
示例相当于以下代码:
1 2 3 4 var paint = Paint();paint.color = Colors.black; paint.strokeCap = StrokeCap.round; paint.strokeWidth = 5.0 ;
以 ?...
开头可确保不会对该空对象进行任何级联操作。
1 2 3 4 5 6 7 querySelector ('#confirm' ) ?..text = 'Confirm' ..classes.add('important' ) ..onClick.listen((e) => { window .alert('Confirmed!' ) }) ..scrollIntoView();
控制流:条件 if 和 else if 1 2 3 4 5 6 7 if (age < 18 ){ print ("Teen" ); } else if ( age > 18 && age <60 ){ print ("Adult" ); } else { print ("Old" ); }
switch case 1 2 3 4 5 6 7 8 9 10 11 12 13 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' ); }
三元操作符 1 2 3 4 int age = 20 ;String message = age >= 18 ? "成人" : "儿童" ;print ("年龄类别: $message " );
三元操作符嵌套使用 1 2 3 4 5 int x = 10 ;int y = 5 ;int result = x > y ? x : y > 0 ? y : 0 ;print ("Result: $result " );
控制流:循环 while 循环 1 2 3 while (!dreamsAchieved) { workHard(); }
循环迭代之前的 while
循环检查条件
do-while 循环 1 2 3 do { workHard(); } while (!dreamsAchieved);
do-while
循环在执行循环内的语句后验证条件
for 循环 1 2 3 4 5 6 7 8 for (int i=0 ; i< 10 ; i++){ print (i); } var numbers = [1 ,2 ,3 ];for (var number in numbers){ print (number); }
Collections Lists 1 2 3 4 5 6 7 8 var list = [1 , 2 , 3 ];print (list.length); print (list[1 ]); List <String > cities = <String >["New York" , "Mumbai" , "Tokyo" ];const constantCities = const ["New York" , "Mumbai" , "Tokyo" ];
Maps 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 var person = Map <String , String >();person['firstName' ] = 'Nicola' ; person['lastName' ] = 'Tesla' ; print (person);print (person['lastName' ]);var nobleGases = { 2 : 'helium' , 10 : 'neon' , 18 : 'argon' , };
Sets 1 2 3 4 5 6 var halogens = {'fluorine' , 'chlorine' , 'bromine' , 'iodine' , 'astatine' };var names = <String >{};Set <String > names = {};
函数 函数示例 1 2 3 4 5 6 7 8 int add(int a, int b){ return a+b; } int sum = add(2 ,3 ); int totalSum = add(2 , add(2 ,3 ));
箭头函数 (=>) 1 2 bool isFav(Product product) => favProductsList.contains(product);
Anonymous (lambda) functions 1 2 3 4 5 6 7 8 9 10 11 12 int add(a,b) => a+b;const list = [ 'apples' , 'bananas' , 'oranges' ]; list.forEach( (item) => print ('${list.indexOf(item)} : $item ' ) );
扩展函数 (Extension) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 extension StringExtension on String { String capitalize() { if (isEmpty) { return this ; } String topStr = this [0 ].toUpperCase(); return '${topStr} ${substring(1 )} ' ; } } void main(List <String > args) { print ("apple" .capitalize()); print ("苹果apple" .capitalize()); }
在不修改 String 类的前提下为其新增了 capitalize 方法
运算符重载 (Extension) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 class Money { final num amount; Money({required this .amount}); } extension MoneyOperatorExtension<T> on Money { Money operator +(Money elements) { Money newMoney = Money(amount: this .amount + elements.amount); return newMoney; } } void main(List <String > args) { Money appleMoney = Money(amount: 10.0 ); Money cardMoney = Money(amount: 6.0 ); Money allMoney = cardMoney + appleMoney; print (allMoney.amount); }
类和对象 类 Class 1 2 3 4 5 6 7 class Cat { String name; void voice(){ print ("Meow" ); } }
对象 Object 1 2 3 4 5 6 7 void main(){ Cat myCat = Cat(); myCat.name = "Kitty" ; myCat.voice(); }
构造函数 1 2 3 4 5 6 7 8 class Cat { String name; Cat(this .name); } void main(){ Cat myCat = Cat("Kitty" ); print (myCat.name); }
抽象类 1 2 3 4 5 6 abstract class AbstractContainer { void updateChildren(); }
Getters Setters 1 2 3 4 5 6 7 8 9 10 11 12 class Cat { String name; String get catName { return name; } void set catName(String name){ this .name = name; } }
隐式接口 一个基本的界面 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 class Person { final String _name; Person(this ._name); String greet(String who) => 'Hello, $who . I am $_name .' ; } 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' ))); print (greetBob(Impostor())); }
扩展类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class Phone { void use(){ _call(); _sendMessage(); } } class SmartPhone extends Phone { void use(){ super .use(); _takePhotos(); _playGames(); } }
枚举 定义枚举 1 enum Color { red, green, blue }
使用枚举,像访问任何其他静态变量一样访问枚举值:
1 2 3 4 final favoriteColor = Color.blue;if (favoriteColor == Color.blue) { print ('Your favorite color is blue!' ); }
枚举中的每个值都有一个索引获取器,它返回枚举声明中值从零开始的位置。 例如,第一个值的索引为 0,第二个值的索引为 1
1 2 3 assert (Color.red.index == 0 );assert (Color.green.index == 1 );assert (Color.blue.index == 2 );
要获取所有枚举值的列表,请使用枚举的值常量
1 2 List <Color> colors = Color.values;assert (colors[2 ] == Color.blue);
您可以在 switch 语句中使用枚举,如果您没有处理枚举的所有值,您将收到警告:
1 2 3 4 5 6 7 8 9 10 11 12 var aColor = Color.blue;switch (aColor) { case Color.red: print ('Red as roses!' ); break ; case Color.green: print ('Green as grass!' ); break ; default : print (aColor); }
如果您需要访问枚举值的名称,例如 Color.blue
中的“blue”,请使用 .name
属性:
枚举示例 声明了一个具有多个实例、实例变量、一个 getter
和一个已实现接口的增强型枚举
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 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 ); const Planet({required this .planetType, required this .moons, required this .hasRings}); final PlanetType planetType; final int moons; final bool hasRings; bool get isGiant => planetType == PlanetType.gas || planetType == PlanetType.ice; } void main(){ final yourPlanet = Planet.mercury; if (!yourPlanet.isGiant) { print ('Your planet is not a "giant planet".' ); } }
Mixin 定义Mixin Dart
中类只能单继承,使用Mixin
可以实现多个继承,复用多个类中代码的方法。
1 2 3 4 5 6 7 8 mixin Piloted { int astronauts = 1 ; void describeCrew() { print ('Number of astronauts: $astronauts ' ); } }
使用with
关键字并在其后跟上Mixin类
的名字来使用
1 2 3 4 class PilotedCraft extends Spacecraft with Piloted { }
支持混入多个Mixin,如果出现相同的方法后混入的Mixin会覆盖前面的
1 2 3 4 5 6 7 8 9 10 11 class Musician extends Performer with Musical { } class Maestro extends Person with Musical , Aggressive , Demented { Maestro(String maestroName) { name = maestroName; canConduct = true ; } }
使用关键字on
来指定哪些类可以使用该Mixin,比如有Mixin类MusicalPerformer
,但是MusicalPerformer
只能被Musician
类使用,则可以这样定义MusicalPerformer
:
1 2 3 4 5 6 7 8 9 10 class Musician { } mixin MusicalPerformer on Musician { } class SingerDancer extends Musician with MusicalPerformer { }
异常 Throw 1 2 3 4 throw IntegerDivisionByZeroException();throw "Product out of stock!" ;
Catch 1 2 3 4 5 6 7 8 9 10 11 12 13 try { int c = 3 /0 ; print (c); } on IntegerDivisionByZeroException { print ('Can not divide integer by 0.' ) } on Exception catch (e) { print ('Unknown exception: $e ' ); } catch (e) { print ('Something really unknown: $e ' ); }
Finally 1 2 3 4 5 6 7 8 try { cookFood(); } catch (e) { print ('Error: $e ' ); } finally { cleanKitchen(); }
Futures Async Await 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Future<String > login() { String userName="Temidjoy" ; return Future.delayed( Duration (seconds: 4 ), () => userName ); } main() async { print ('Authenticating please wait...' ); print (await userName()); }
各种各样的 Null 和 Null 感知 1 2 3 4 5 6 7 int x; x ??=6 ; print (x); x ??=3 ; print (x); print (null ?? 10 );
三元运算符 1 2 3 bool isAvailable;isAvailable ? orderproduct() : addToFavourite();
条件属性访问 1 2 3 4 5 6 userObject?.userName (userObject != null ) ? userObject.userName : null userObject?.userName?.toString()
扩展运算符 (…) 1 2 3 4 var list = [1 , 2 , 3 ];var list2 = [0 , ...list];print (list2.length);
enum 定义:enum(”enumeration”的缩写)是一种特殊的数据类型,可使变量成为一组预定义的常量。枚举用于定义只能从一小组可能值中选择一个的变量。通过为这些值集提供有意义的名称,枚举有助于提高代码的可读性,减少出错率。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 enum TrafficLight { red, yellow, green } void printTrafficLightMessage(TrafficLight light) { switch (light) { case TrafficLight.red: print ('Stop!' ); break ; case TrafficLight.yellow: print ('Get ready...' ); break ; case TrafficLight.green: print ('Go!' ); break ; } } void main() { TrafficLight currentLight = TrafficLight.green; printTrafficLightMessage(currentLight); }
级联符号 (..) 1 2 3 4 5 6 7 8 9 10 11 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 ;
延迟初始化 1 2 3 4 5 6 7 8 9 10 late String token;void main(List <String > args) { token = "tokenContent" ; print (token); }
另见