Skip to content

Instantly share code, notes, and snippets.

@Josscii
Last active September 9, 2021 23:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Josscii/8e1803c50ac45ccf20b0afbd138294dc to your computer and use it in GitHub Desktop.
Save Josscii/8e1803c50ac45ccf20b0afbd138294dc to your computer and use it in GitHub Desktop.
dart cheat sheet

string interpolation

var a = 3;
print("$a 123");
print("${a+1} 123");

final const

final a = [];
a = [1]; // error
a.add(2); // ok

const b = [];
b = [1]; // error
b.add(2); // error

var c = const [];
c = [1]; // ok
c.add(2); // error

function

required positional parameters 后面只能跟 named parameters 或者 optional positional parameters,不能同时出现。

optional parameter 只能是 nullable 或者给 default value。

parameters

required positional parameters

int test(int? a, int? b) {} 
test(3, 4); // ok

optional named parameters

int test(int? a, {int? b, int? c}) {}
test(3, b: 4, c: 3); // ok
test(3); // ok
test(3, b: 4); // ok

required named parameters

int test(int? a, {int? b, required int? c}) {}
test(3, b: 4, c: 3); // ok
test(3, c: 4); // ok
test(3); // error

optional positional parameters

int test(int? a, [int? b]) {}
test(a, b); // ok
test(a); //ok

arrow syntax

dart 不支持 arrow function,只是当 function 只有一句返回语句时,可以简写成 arrow syntax。

int test() { return 3; }
test() => 3;

anonymous functions

var list = ['apples', 'bananas', 'oranges'];
list.forEach((item) {
  print('${list.indexOf(item)}: $item');
});

operator

  1. ??
int? a;
int b = a ?? 0;
// b = 0
  1. ??=
int? b = 3;
b ??= 2;
// b = 3
  1. .. / ?..
querySelector('#confirm') // Get an object.
  ?..text = 'Confirm' // Use its members.
  ..classes.add('important')
  ..onClick.listen((e) => window.alert('Confirmed!'));

class

constructor

dart 的非 late instance variable 必须在 constructor body 执行之前初始化,三种方式:

  1. 赋初始值。
  2. 用 constructor 的 this 语法,可以和普通参数一起使用。
  3. 用 initializer list。
class Parent {
  int x;
  int? y;
  late int z;
  int a = 0;
  
  Parent(this.x, int z) {
    this.z = z;
  }
  
  Parent.init(int x) : x = x {
    this.z = 0;
  }
  
  Parent.init2({int x = 3}) : x = x {
    this.z = 0;
  }
  
  void printSelf() {
    print(this);
  } 
} 

default no-name no-args constructor

一个类在不声明其他 constructor 的情况下,会有一个默认的无名无参的 constructor。

no inherited constructor

子类不会继承父类的初始化函数。

call super constructor

如果父类有无名无参的 constructor,子类 constructor 会默认隐式调用。 否则,子类必须在 : 后面显式调用 super。

redirecting constructor

一个类的 constructor 可以在 : 后通过 this 调用自己的 constructor,这时候不需要提供 body。

constant constructor

如果一个类的所有成员变量都是 final 的,那么可以在 constructor 前加 const 来定义 constant constructor,这样通过它创建的对象都是同一个。

factory constructor

一个特殊的 constructor,返回一个本类或者子类的对象,有点类似于类函数,不能访问 this。

getter setter

class CustomGetterSetter {
  int _a = 3;
  int get a => _a;
  set a(int value) => _a = value;
  
  int get b => _a + 1;
}

extending a class

用 extends 创建子类,@override 重写实例方法或者变量。

class Child extends Parent {
  Child(this.a) : super.init2();
  
  @override
  int a;
  
  @override
  void printSelf() {
    print("super");
  }
}

abstract classes

abstract class 可以定义没有 body 的函数,其他和普通的 class 没有区别。

abstract class AbstractContainer {
  void updateChildren(); 
}

implicit interfaces

一个类,无论是 abstract 的还是非 abstract 的,都默认会生成一个 interface,其他的类可以实现它。

class ConcreteChild implements AbstractContainer {
 void updateChildren() {} 
}

extension methods

/*
 extension <extension name> on <type> {
  (<member definition>)*
 }
 */
extension ChildExtension on Child {
  void extensionMethod() {
    print("extensionMethod");
  }
}

Class variables and methods

用 static 定义。

class Child extends Parent {
  //...
  static int classVal = 3;
  static void classMet() {
    print("classMet")
  }
}

collection

var arr = <int>[];
arr.add(3);
  
var map = <String, int>{};
map["age"] = 3;
  
var set = <String>{};
set.add("1");

libraries and visibility

_ 开头的 identifier 只在当前 library 可见。

// 当前 library
import 'test.dart';

// 自带 library dart:
import 'dart:html';

// 其他 library package:
import 'package:test/test.dart';

// 增加前缀
import 'package:lib2/lib2.dart' as lib2;
lib2.Element element2 = lib2.Element();

// Import only foo.
import 'package:lib1/lib1.dart' show foo;

// Import all names EXCEPT foo.
import 'package:lib2/lib2.dart' hide foo;
@Josscii
Copy link
Author

Josscii commented Sep 1, 2021

json 解析:

  1. 范型不指定类型就是 dynamic。
  2. jsonDecode 解析如果是 Map 类型就是 Map<String, dynamic>,是 List 类型就是 List。
  3. List 无法用 as 转换为固定类型的 List,比如 List,可以用 List.from 或者 list.cast() 或者 List.castFrom,map 同理。
  4. 其他基础类型可以用 as 转换,如果字段可能不存在,可以用类似 as int? 的方式,还可以加上 ?? 来给默认值。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment