基础知识篇
- const 和 final
对象都是只能赋值一次,但是const对象的内容也不可变。
List constList = const [1, 2, 'hello'];
// 下面这行编译不通过
//constList[0] = 2;
final List finalList = [1, 2, 'hello'];
// 这行可以编译通过
finalList[0] = 2;
-
与除法相关的运算符
/ 表示除,除出来的结果是一个double类型,~/ 表示取整,除出来的结果是一个整数,% 与其他语言一样,是取余。 -
数值类型,如果没有赋值,则默认为null,而不是0,如:
int a;
print(a);
则会打印null
-
查看某个对象所有的函数
Ctrl + F12 -
赋值运算符??=
表示如果为null则进行赋值,反之则不赋值 -
条件表达式??
exp1 ?? exp2
如果exp1不为空,则使用exp1,否则使用exp2
-
对象操作符 ?.
如果对象为空,则不调用方法,反之则调用,用于避免空指针 -
对象操作符is 和 is!
省去强转 -
级联操作符…
类似builder模式,意思是给当前对象的属性赋值,然后返回当前对象,可以多次使用该操作符来实现属性赋值和方法调用
Person()
..name = "Tom"
..age = 20
..work();
-
箭头语法=>
适用于返回一个表达式的方法 -
闭包
闭包是一个方法(对象),闭包是定义在其他方法内部的方法,闭包可以访问外部方法内的局部变量,并持有其状态,通过闭包可以把方法内部的局部变量暴露出去,供其他对象使用。
void main(){
var func = a();
func();
func();
func();
func();
}
a(){
int count = 0;
// printCount(){
// print(count++);
// }
return (){
print(count++);
};
}
-
可见性
每个dart都是一个库(library),类加上下划线_则表示该类是私有的,仅在该dart文件中可见。其他方法、变量类似。 -
构造方法语法糖
class Person{
String name;
int age;
final String gender;
// 使用了语法糖,把传入的参数直接赋值到对应的变量里去,赋值操作会在构造方法执行之前执行(语法糖可以对final修饰的变量进行赋值)
Person(this.name,this.age,this.gender);
// 也可以写成如下:Person(this.name,this.age,this.gender) {...}
// 使用命名的构造方法,可以实现多个构造方法(类名.方法)
Person.withName(String name){
this.name = name;
}
Person.withAge(this.age);
void work(){
print("Work...");
}
}
-
常量构造方法
如果要求类的状态不可变,只需要赋值一次,可以吧对象定义为编译时的常量,使用const声明构造方法,并且所有变量都是final的。然后使用const声明对象,也可以省略这个const。 -
初始化列表
跟在构造方法后面,在构造方法(包括父类的)执行前执行,常用于设置final变量的值
void main() {
var person = new Person("Tom", 20, "Male");
}
class Person{
String name;
int age;
final String gender;
Person(this.name,this.age,this.gender);
Person.withMap(Map map): name = map["name"],gender = map["gender"]{
age = map["age"];
}
void work(){
print("Work...");
}
}
-
多态
子类的示例赋值给父类的引用 -
抽象类
dart的抽象类更像其他语言的接口
void main() {
var person = new Student();
person.run();
}
abstract class Person{
void run();
}
class Student extends Person{
@override
void run() {
print("run...");
}
}
- 接口
类和接口是统一的,dart中的类就是接口,非要使用dart的接口,则使用抽象类的形式定义的接口(父类不要使用普通类,不要定义一些变量)
void main() {
var student = new Student();
student.run();
}
//class Person{
// String name;
//
// int get age => 18;
//
// void run(){
// print("Person run...");
// }
//}
abstract class Person{
void run();
}
class Student implements Person{
@override
void run() {
print("Student run...");
}
}
- Mixins
类似于多继承,是在多类继承中重用一个类代码的方式,有两种实现方式,一种是基于继承的完整写法,一种是简写(针对没有更多额外的方法即最终的类没有更多特殊的方法时可以使用)
使用关键字with连接一个或多个mixin
如果方法相同,以with里最后一个类的方法为准;
作为Mixin的类(被使用的类)不能有显式声明的构造方法;
作为Mixin的类只能继承自Object(即不能extends其他类,但是可以implements其他类)
void main() {
// var d = new D();
// d.a();
}
//class A{
// void a(){
// print("A.a()...");
// }
//}
//
//class B{
//
// void a(){
// print("B.a()...");
// }
//
// void b(){
// print("B.b()...");
// }
//}
//
//class Test{}
//
//
//class C{
//
// void a(){
// print("C.a()...");
// }
//
// void b(){
// print("C.b()...");
// }
//
// void c(){
// print("C.c()...");
// }
//}
//
//class D extends A with C,B{
//
//}
abstract class Engine{
void work();
}
class OilEngine implements Engine{
@override
void work() {
print("Work with oil...");
}
}
class ElectricEngine implements Engine{
@override
void work() {
print("Work with Electric...");
}
}
class Tyre{
String name;
void run(){}
}
class Car = Tyre with ElectricEngine;
class Bus = Tyre with OilEngine;
- 泛型
void main() {
var list = new List<int>();
list.add(1);
// var utils = new Utils<int>();
// utils.put(1);
var utils = new Utils();
utils.put<int>(1);
}
class Utils{
void put<T>(T element){
print(element);
}
// void putString(String element){
// this.elementStr = element;
// }
}
开发规范篇
参考阿里巴巴Flutter Go 代码开发规范 0.1.0 版
- 代码检查插件,可以在pubspec.yaml同级目录下新增analysis_options.yaml文件,内容如下:
analyzer:
strong-mode:
implicit-casts: false
errors:
avoid_returning_null_for_future: warning
cancel_subscriptions: warning
dead_code: warning
override_on_non_overriding_method: warning
unused_element: warning
unused_import: warning
avoid_empty_else: warning
exclude:
- test/**
linter:
rules:
- camel_case_types
- library_names
- library_prefixes
- file_names
- package_names
- non_constant_identifier_names
- constant_identifier_names
- sort_pub_dependencies
- directives_ordering
- curly_braces_in_flow_control_structures
- slash_for_doc_comments
- package_api_docs
- public_member_api_docs
- comment_references
- prefer_adjacent_string_concatenation
- prefer_interpolation_to_compose_strings
- unnecessary_brace_in_string_interps
- prefer_collection_literals
- prefer_is_empty
- prefer_is_not_empty
- prefer_for_elements_to_map_fromIterable
- avoid_function_literals_in_foreach_calls
- prefer_equal_for_default_values
- avoid_init_to_null
- unnecessary_getters_setters
- unnecessary_this
- prefer_initializing_formals
- unnecessary_new
- unnecessary_await_in_return
- avoid_void_async
更丰富的提示参考官方代码分析提示
标识符三种类型
大驼峰
类、枚举、typedef和类型参数
class SliderMenu { ... }
class HttpRequest { ... }
typedef Predicate = bool Function<T>(T value);
包括用于元数据注释的类
class Foo {
const Foo([arg]);
}
@Foo(anArg)
class A { ... }
@Foo()
class B { ... }
使用小写加下划线来命名库和源文件
library peg_parser.source_scanner;
import 'file_system.dart';
import 'slider_menu.dart';
不推荐如下写法:
library pegparser.SourceScanner;
import 'file-system.dart';
import 'SliderMenu.dart';
使用小写加下划线来命名导入前缀
import 'dart:math' as math;
import 'package:angular_components/angular_components'
as angular_components;
import 'package:js/js.dart' as js;
不推荐如下写法:
import 'dart:math' as Math;
import 'package:angular_components/angular_components'
as angularComponents;
import 'package:js/js.dart' as JS;
使用小驼峰法命名其他标识符
var item;
HttpRequest httpRequest;
void align(bool clearItems) {
// ...
}
优先使用小驼峰法作为常量命名
const pi = 3.14;
const defaultTimeout = 1000;
final urlScheme = RegExp('^([a-z]+):');
class Dice {
static final numberGenerator = Random();
}
不推荐如下写法:
const PI = 3.14;
const DefaultTimeout = 1000;
final URL_SCHEME = RegExp('^([a-z]+):');
class Dice {
static final NUMBER_GENERATOR = Random();
}
不使用前缀字母
因为Dart可以告诉您声明的类型、范围、可变性和其他属性,所以没有理由将这些属性编码为标识符名称。
defaultTimeout
不推荐如下写法:
kDefaultTimeout
排序
为了使你的文件前言保持整洁,我们有规定的命令,指示应该出现在其中。每个“部分”应该用空行分隔。
在其他引入之前引入所需的dart库
import 'dart:async';
import 'dart:html';
import 'package:bar/bar.dart';
import 'package:foo/foo.dart';
在相对引入之前先引入在包中的库
import 'package:bar/bar.dart';
import 'package:foo/foo.dart';
import 'util.dart';
第三方包的导入先于其他包
import 'package:bar/bar.dart';
import 'package:foo/foo.dart';
import 'package:my_package/util.dart';
在所有导入之后,在单独的部分中指定导出
import 'src/error.dart';
import 'src/foo_bar.dart';
export 'src/error.dart';
不推荐如下写法:
import 'src/error.dart';
export 'src/error.dart';
import 'src/foo_bar.dart';
所有流控制结构,请使用大括号
这样做可以避免悬浮的else问题
if (isWeekDay) {
print('Bike to work!');
} else {
print('Go dancing or read a book!');
}
例外
一个if语句没有else子句,其中整个if语句和then主体都适合一行。在这种情况下,如果你喜欢的话,你可以去掉大括号
if (arg == null) return defaultValue;
如果流程体超出了一行需要分划请使用大括号:
if (overflowChars != other.overflowChars) {
return overflowChars < other.overflowChars;
}
不推荐如下写法:
if (overflowChars != other.overflowChars)
return overflowChars < other.overflowChars;
注释
要像句子一样格式化
除非是区分大小写的标识符,否则第一个单词要大写。以句号结尾(或“!”或“?”)。对于所有的注释都是如此:doc注释、内联内容,甚至TODOs。即使是一个句子片段。
greet(name) {
// Assume we have a valid name.
print('Hi, $name!');
}
不推荐如下写法:
greet(name) {
/* Assume we have a valid name. */
print('Hi, $name!');
}
可以使用块注释(/…/)临时注释掉一段代码,但是所有其他注释都应该使用//
Doc注释
使用///文档注释来记录成员和类型。
使用doc注释而不是常规注释,可以让dartdoc找到并生成文档。
/// The number of characters in this chunk when unsplit.
int get length => ...
!!!
由于历史原因,达特茅斯学院支持道格评论的两种语法:///(“C#风格”)和/**…* /(“JavaDoc风格”)。我们更喜欢/// 因为它更紧凑。/**和*/在多行文档注释中添加两个无内容的行。在某些情况下,///语法也更容易阅读,例如文档注释包含使用*标记列表项的项目符号列表。!!!
考虑为私有api编写文档注释
Doc注释并不仅仅针对库的公共API的外部使用者。它们还有助于理解从库的其他部分调用的私有成员
用一句话总结开始doc注释
以简短的、以用户为中心的描述开始你的文档注释,以句号结尾。
/// Deletes the file at [path] from the file system.
void delete(String path) {
...
}
不推荐如下写法:
/// Depending on the state of the file system and the user's permissions,
/// certain operations may or may not be possible. If there is no file at
/// [path] or it can't be accessed, this function throws either [IOError]
/// or [PermissionError], respectively. Otherwise, this deletes the file.
void delete(String path) {
...
}
“doc注释”的第一句话分隔成自己的段落
在第一个句子之后添加一个空行,把它分成自己的段落
/// Deletes the file at [path].
///
/// Throws an [IOError] if the file could not be found. Throws a
/// [PermissionError] if the file is present but could not be deleted.
void delete(String path) {
...
}
Flutter_Go 使用参考
库的引用
flutter go 中,导入lib下文件库,统一指定包名,避免过多的../../
package:flutter_go/
字符串的使用
①普通字符串建议使用单引号括起来,而不是双引号,当然非要使用双引号也是没有错误的,习惯问题。
②使用三个引号(三个单引号或三个双引号都可以)创建多行字符串
String str = '''Hello
Dart''';
③使用r创建原始raw字符串
// 如果没有r,则转义字符会生效(换行)
String rawStr = r'Hello \n Dart';
④判断字符串内容是否相同使用==操作符
使用相邻字符串连接字符串文字
如果有两个字符串字面值(不是值,而是实际引用的字面值),则不需要使用+连接它们。就像在C和c++中,简单地把它们放在一起就能做到。这是创建一个长字符串很好的方法但是不适用于单独一行。
raiseAlarm(
'ERROR: Parts of the spaceship are on fire. Other '
'parts are overrun by martians. Unclear which are which.');
不推荐如下写法:
raiseAlarm('ERROR: Parts of the spaceship are on fire. Other ' +
'parts are overrun by martians. Unclear which are which.');
优先使用模板字符串
'Hello, $name! You are ${year - birth} years old.';
在不需要的时候,避免使用花括号
'Hi, $name!'
"Wear your wildest $decade's outfit."
不推荐如下写法:
'Hello, ' + name + '! You are ' + (year - birth).toString() + ' y...';
不推荐如下写法:
'Hi, ${name}!'
"Wear your wildest ${decade}'s outfit."
集合
尽可能使用集合字面量
如果要创建一个不可增长的列表,或者其他一些自定义集合类型,那么无论如何,都要使用构造函数。
var points = [];
var addresses = {};
var lines = <Lines>[];
不推荐如下写法:
var points = List();
var addresses = Map();
不要使用.length查看集合是否为空
if (lunchBox.isEmpty) return 'so hungry...';
if (words.isNotEmpty) return words.join(' ');
不推荐如下写法:
if (lunchBox.length == 0) return 'so hungry...';
if (!words.isEmpty) return words.join(' ');
考虑使用高阶方法转换序列
如果有一个集合,并且希望从中生成一个新的修改后的集合,那么使用.map()、.where()和Iterable上的其他方便的方法通常更短,也更具有声明性
var aquaticNames = animals
.where((animal) => animal.isAquatic)
.map((animal) => animal.name);
避免使用带有函数字面量的Iterable.forEach()
在Dart中,如果你想遍历一个序列,惯用的方法是使用循环。
for (var person in people) {
...
}
不推荐如下写法:
people.forEach((person) {
...
});
不要使用List.from(),除非打算更改结果的类型
给定一个迭代,有两种明显的方法可以生成包含相同元素的新列表
var copy1 = iterable.toList();
var copy2 = List.from(iterable);
明显的区别是第一个比较短。重要的区别是第一个保留了原始对象的类型参数
// Creates a List<int>:
var iterable = [1, 2, 3];
// Prints "List<int>":
print(iterable.toList().runtimeType);
// Creates a List<int>:
var iterable = [1, 2, 3];
// Prints "List<dynamic>":
print(List.from(iterable).runtimeType);
参数的使用
使用=将命名参数与其默认值分割开
由于遗留原因,Dart均允许“:”和“=”作为指定参数的默认值分隔符。为了与可选的位置参数保持一致,使用“=”。
void insert(Object item, {int at = 0}) { ... }
不推荐如下写法:
void insert(Object item, {int at: 0}) { ... }
不要使用显式默认值null
如果参数是可选的,但没有给它一个默认值,则语言隐式地使用null作为默认值,因此不需要编写它
void error([String message]) {
stderr.write(message ?? '\n');
}
不推荐如下写法:
void error([String message = null]) {
stderr.write(message ?? '\n');
}
变量
不要显式地将变量初始化为空
在Dart中,未显式初始化的变量或字段自动被初始化为null。不要多余赋值null
int _nextId;
class LazyId {
int _id;
int get id {
if (_nextId == null) _nextId = 0;
if (_id == null) _id = _nextId++;
return _id;
}
}
不推荐如下写法:
int _nextId = null;
class LazyId {
int _id = null;
int get id {
if (_nextId == null) _nextId = 0;
if (_id == null) _id = _nextId++;
return _id;
}
}
避免储存你能计算的东西
在设计类时,您通常希望将多个视图公开到相同的底层状态。通常你会看到在构造函数中计算所有视图的代码,然后存储它们:
应该避免的写法:
class Circle {
num radius;
num area;
num circumference;
Circle(num radius)
: radius = radius,
area = pi * radius * radius,
circumference = pi * 2.0 * radius;
}
如上代码问题:
- 浪费内存
- 缓存的问题是无效——如何知道何时缓存过期需要重新计算?
推荐的写法如下:
class Circle {
num radius;
Circle(this.radius);
num get area => pi * radius * radius;
num get circumference => pi * 2.0 * radius;
}
类成员
不要把不必要的字段包装在getter和setter中
不推荐如下写法:
class Box {
var _contents;
get contents => _contents;
set contents(value) {
_contents = value;
}
}
优先使用final字段来创建只读属性
尤其对于 StatelessWidget
在不需要的时候不要用this
不推荐如下写法:
class Box {
var value;
void clear() {
this.update(null);
}
void update(value) {
this.value = value;
}
}
推荐如下写法:
class Box {
var value;
void clear() {
update(null);
}
void update(value) {
this.value = value;
}
}
构造函数
尽可能使用初始化的形式
不推荐如下写法:
class Point {
num x, y;
Point(num x, num y) {
this.x = x;
this.y = y;
}
}
推荐如下写法:
class Point {
num x, y;
Point(this.x, this.y);
}
不要使用new
Dart2使new 关键字可选
推荐写法:
Widget build(BuildContext context) {
return Row(
children: [
RaisedButton(
child: Text('Increment'),
),
Text('Click!'),
],
);
}
不推荐如下写法:
Widget build(BuildContext context) {
return new Row(
children: [
new RaisedButton(
child: new Text('Increment'),
),
new Text('Click!'),
],
);
}
异步
优先使用async/await代替原始的futures
async/await语法提高了可读性,允许你在异步代码中使用所有Dart控制流结构。
Future<int> countActivePlayers(String teamName) async {
try {
var team = await downloadTeam(teamName);
if (team == null) return 0;
var players = await team.roster;
return players.where((player) => player.isActive).length;
} catch (e) {
log.error(e);
return 0;
}
}
当异步没有任何用处时,不要使用它
如果可以在不改变函数行为的情况下省略异步,那么就这样做。、
Future afterTwoThings(Future first, Future second) {
return Future.wait([first, second]);
}
不推荐写法:
Future afterTwoThings(Future first, Future second) async {
return Future.wait([first, second]);
}