Dart是一种基于类的可选类型化编程语言,设计用于创建Web应用程序。
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');
}
class MyColor {
int red;
int green;
int blue;
MyColor(this.red, this.green, this.blue);
}
final color = MyColor(80, 80, 128);
class ImmutablePoint {
static const ImmutablePoint origin = ImmutablePoint(0, 0);
final int x;
final int y;
const ImmutablePoint(this.x, this.y);
}
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;
}
腾图小抄 SCWY.net v0.03 小抄561条 自2022-01-02访问317639次