本文主要介绍Dart 基础知识笔记。
main() 函数是 Dart 程序的入口main() 函数返回 void 并具有可选的 List<String> 参数作为参数Object 类继承dynamicvar name = 'Bob'; 这里的 name 类型推断为 Stringnull,包括数字类型Runesvar s = r'In a raw stringList 对象var halogens = {'fluorine', 'chlorine'}{} 默认为 Map 类型,var names = {}; 创建了 Map 而不是 Setnew 关键字是可选的 (Dart 2开始)Function,可以将函数分配给变量或作为参数传递给其他函数=> expr 用于简化仅包含一个表达式的函数= 来定义命名参数和位置参数的默认值。默认值必须是编译时常量~/ 返回除法的整数结果switch 语句使用 == 比较整数、字符串、枚举或编译时常量Exception 和 Error 类型,并且支持将任何非 null 对象作为异常抛出runtimeType 属性返回对象类型async/await 关键字处理 Future 结果await for 处理 Stream 结果// 延迟导入库
import 'package:greetings/hello.dart' deferred as hello;
// 使用库
Future greet() async {
await hello.loadLibrary();
hello.printGreeting();
}开发过程中可以使用 assert(condition , optionalMessage) 断言,检查某些条件是否为真。断言通常由工具或框架决定是否生效:
--enable-asserts 标志启用断言Dart 中的构造函数跟 Java 中的构造函数还是有不小的区别,所以值得独立作为一节来讨论。
这里先列出了 Dart 构造函数相关的一些术语。
如果你清楚这些术语,说明你已经基本掌握了 Dart 构造函数,完全可以略过本节。如果不清楚,不妨往下看。
Dart 中通过创建一个与其类具有相同名称的函数来声明一个构造函数。可以很方便地将构造函数参数赋值给实例变量:
class Point {
num x, y;
// Syntactic sugar for setting x and y
// before the constructor body runs.
Point(this.x, this.y);
}Dart 中使用命名构造函数可为一个类实现多个构造函数或提供额外的清晰度:
class Point {
num x, y;
Point(this.x, this.y);
// Named constructor
Point.origin() {
x = 0;
y = 0;
}
}构建函数的执行顺序如下:
注意:如果超类没有未命名,无参数的构造函数,则必须手动调用超类中的构造函数之一
class Employee extends Person {
Employee() : super.fromJson(getDefaultData());
// ···
}在实现并非总是创建其类的新实例的构造函数时,要使用 factory 关键字。示例如下:
class Logger {
final String name;
bool mute = false;
// _cache is library-private, thanks to
// the _ in front of its name.
static final Map<String, Logger> _cache =
<String, Logger>{};
factory Logger(String name) {
return _cache.putIfAbsent(
name, () => Logger._internal(name));
}
Logger._internal(this.name);
void log(String msg) {
if (!mute) print(msg);
}
}每个类都隐式定义一个接口。
// A person. The implicit interface contains greet().
class Person {
// In the interface, but visible only in this library.
final _name;
// Not in the interface, since this is a constructor.
Person(this._name);
// In the interface.
String greet(String who) => 'Hello, $who. I am $_name.';
}
// An implementation of the Person interface.
class Impostor implements Person {
get _name => '';
String greet(String who) => 'Hi $who. Do you know who I am?';
}Mixins是在多个类层次结构中重用类代码的一种方式。
首先看如何实现 mixin。使用 mixin 关键字创建一个扩展自 Object 且不声明构造函数的类。还可以使用 on 关键字来限定可以使用该 mixin 的类
mixin Musical {
bool canPlayPiano = false;
bool canCompose = false;
bool canConduct = false;
void entertainMe() {
if (canPlayPiano) {
print('Playing piano');
} else if (canConduct) {
print('Waving hands');
} else {
print('Humming to self');
}
}
}
mixin MusicalPerformer on Musician {
// ···
}再来看如何使用 mixin
从设计者角度来说是一些锦上添花的语言特性,但从开发者角度来确实很方便。
类型推断
num highScore(List<num> scores) {
var highest = 0;
for (var score in scores) {
if (score > highest) highest = score;
}
return highest;
}扩展操作符 ...
var list = [1, 2, 3];
var list2 = [0, ...list];
assert(list2.length == 4);nullable 扩展操作符 ...?
var list;
var list2 = [0, ...?list];
assert(list2.length == 1);命名参数 (Named parameters) paramName : value
// 定义命名参数
/// Sets the [bold] and [hidden] flags ...
void enableFlags({bool bold, bool hidden}) {...}
// 指定命名参数
enableFlags(bold: true, hidden: false);位置参数 (Positional parameters)
// 使用[]标记一组可选的位置参数
String say(String from, String msg, [String device]) {
...
}级联操作符 ..。这个操作符可以节省创建临时变量的步骤。
void main() {
querySelector('#sample_text_id')
..text = 'Click me!'
..onClick.listen(reverseText);
}匿名函数
var list = ['apples', 'bananas', 'oranges'];
list.forEach((item) {
print('${list.indexOf(item)}: $item');
});??= 操作符。这个操作符让代码更简洁
// Assign value to b if b is null; otherwise, b stays the same
b ??= value;?? 操作符。这个操作符让代码更简洁
// 如果 name 为 null 则返回 'Guest'
String playerName(String name) => name ?? 'Guest';?. 操作符,表示有条件的成员访问,最左边的操作数可以为 null
typedef 用于给函数类型提供一个名称
typedef Compare = int Function(Object a, Object b);
class SortedCollection {
Compare compare;
SortedCollection(this.compare);
}
// Initial, broken implementation.
int sort(Object a, Object b) => 0;
void main() {
SortedCollection coll = SortedCollection(sort);
assert(coll.compare is Function);
assert(coll.compare is Compare);
}operator 来重载操作符call() 方法的类,可以像调用函数一样调用该类的实例原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。