dart】 Dart编程语言【dart】


Dart是一种基于类的可选类型化编程语言,设计用于创建Web应用程序。

资源

官网

Dart 编程语言中文网

Dart中文站

语法

可空的变量

int? a = null;

避空运算符

print(null ?? 12); <-- Prints 12.

条件属性访问

myObject?.someProperty

等效于:

(myObject != null) ? myObject.someProperty : null

集合字面量

final aListOfStrings = ['one', 'two', 'three'];

final aSetOfStrings = {'one', 'two', 'three'};

final aMapOfStringsToInts = {

  'one': 1,

  'two': 2,

  'three': 3,

};

箭头语法

bool hasEmpty = aListOfStrings.any((s) {

  return s.isEmpty;

});

等价于:

bool hasEmpty = aListOfStrings.any((s) => s.isEmpty);

级联

调用 someMethod 方法,而表达式的结果是 someMethod 的返回值

myObject..someMethod()

可选位置参数

int sumUpToFive(int a, [int? b, int? c, int? d, int? e]) {

  int sum = a;

  if (b != null) sum += b;

  if (c != null) sum += c;

  if (d != null) sum += d;

  if (e != null) sum += e;

  return sum;

}

···

  int total = sumUpToFive(1, 2);

  int otherTotal = sumUpToFive(1, 2, 3, 4, 5);

int sumUpToFive(int a, [int b = 2, int c = 3, int d = 4, int e = 5]) {

···

}

···

  int newTotal = sumUpToFive(1);

  print(newTotal); <-- prints 15

可选命名参数

void printName(String firstName, String lastName, {String? suffix}) {

  print('$firstName $lastName ${suffix ?? ''}');

}

···

  printName('Avinash', 'Gupta');

  printName('Poshmeister', 'Moneybuckets', suffix: 'IV');

异常

try {

  breedMoreLlamas();

} on OutOfLlamasException {

   A specific exception

  buyMoreLlamas();

} on Exception catch (e) {

   Anything else that is an exception

  print('Unknown exception: $e');

} catch (e) {

   No specified type, handles all

  print('Something really unknown: $e');

}

在构造方法中使用 this

class MyColor {

  int red;

  int green;

  int blue;

  MyColor(this.red, this.green, this.blue);

}

final color = MyColor(80, 80, 128);

Const 构造方法

class ImmutablePoint {

  static const ImmutablePoint origin = ImmutablePoint(0, 0);

  final int x;

  final int y;

  const ImmutablePoint(this.x, this.y);

}

示例

hello world

main() {

    print('Hello World!');

}

异步并发示例

import 'dart:async';

import 'dart:isolate';

main() async {

  var receivePort = new ReceivePort();

  await Isolate.spawn(echo, receivePort.sendPort);

   'echo'发送的第一个message,是它的SendPort

  var sendPort = await receivePort.first;

  var msg = await sendReceive(sendPort, "foo");

  print('received $msg');

  msg = await sendReceive(sendPort, "bar");

  print('received $msg');

}

/ 新isolate的入口函数

echo(SendPort sendPort) async {

   实例化一个ReceivePort 以接收消息

  var port = new ReceivePort();

   把它的sendPort发送给宿主isolate,以便宿主可以给它发送消息

  sendPort.send(port.sendPort);

   监听消息

  await for (var msg in port) {

    var data = msg[0];

    SendPort replyTo = msg[1];

    replyTo.send(data);

    if (data == "bar") port.close();

  }

}

/ 对某个port发送消息,并接收结果

Future sendReceive(SendPort port, msg) {

  ReceivePort response = new ReceivePort();

  port.send([msg, response.sendPort]);

  return response.first;

}

分类列表:


  1. dart

腾图小抄 SCWY.net v0.03 小抄561条 自2022-01-02访问317639次