Skip to content

Instantly share code, notes, and snippets.

@SongFuZhen
Last active October 26, 2020 09:54
Show Gist options
  • Save SongFuZhen/bcda0f59669a24b6825ae3dc733d99c8 to your computer and use it in GitHub Desktop.
Save SongFuZhen/bcda0f59669a24b6825ae3dc733d99c8 to your computer and use it in GitHub Desktop.

Dart编码规范

样式规范

类、枚举、类型定义和泛型,都需要大写开头的驼峰命名法

class Login 
typedef Predicate<T> = bool Function(T value);

class Foo() {
  const Foo([args])
}

@Foo(anArg)
class A {
  /// ...
}

@Foo()
class B {
  /// ...
}

命名库、包、目录、dart文件都应该是小写加下划线

library peg_parser.source_scanner;

import 'file_system.dart';

将引用使用as转换的名字也需要小写加下划线

import 'dart:math' as math;
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]+):');

文档规范

注释使用///

使用一句简明扼要的话作为开头 空一格 将参数和返回值使用[]加持

/// Delete the file at [path] from the file system.
///
/// 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){
  ...
}

使用规范

使用相对路径导入依赖

import 'src/utils.dart';

使用??将null值做一个转换

/// Define isEnabled Params
///
/// return false if isEnabled is null
optionalThing?.isEnabled ?? false

字符串

dart中,不需要使用+连接字符串

raiseAlarm(
    'ERROR: Parts of the spaceship are on fire. Other '
    'parts are overrrun by ....');

使用${}连接字符串和变量

'Hello, $name! You are ${year - birthday} years old. '

集合

尽可能使用简单的字面量创建集合

var points = [];
var addressses = {};

/// 指定类型
var points = <Point>[];
var addresses = <String, Address>{};

使用isEmpty或isNotEmpty判断集合是否为空

if(lunchBox.isEmpty) return 'so hungry...'
if(words.isNotEmpty) return words.join(' ');

使用高阶方法转换序列

var aquaticNames = animals
    .where((animal) => animal.isAquatic)
    .map((animal) => animal.name);

不要使用List.from() 除非打算更改结果的类型

有两种方法可以获取Iterable,分别是List.from() 和 Iterable.toList()

/// 创建一个List<int>
var iterable = [1, 2, 3];

/// 输出`List<int>`
///
/// 如果使用List.from的话,会输出`List<dynamic>`
print(iterable.toList().runtimeType);

使用whereType()去用类型过滤一个集合

var objects = [1, 'a', 'b2', 2];

var ints = objects.whereType<int>();

参数

给参数设置默认值

void insert(Object item, { int at = 0 }) { ... }

不要讲参数的默认值设置为null

变量

不存储可以计算的值

class Circle {
  num radius;
  Circle (this.radius);
  
  num get area = pi * radius * radius;
  num get circumference = pi * 2.0 * radius;
}

成员

不需要些没必要的gettersetter

class Box {
  void contents;
}

构造函数

尽可能使用简单的初始化形式

class Point {
  num x, y;
  Point(this.x, this.y);
}

不要使用new创建对象

Widget build(BuildContext context) {
  return Row(
    children: [
      RaisedButton(
        child: Text('Increment'),
      ),
      Text('Click!'),
    ],
  );
}

#异常处理

使用rethrow重新抛出异常

try {
  somethingRisky();
} catch (e) {
  if (!canHandle(e)) rethrow;
  handle(e);
}

设计

避免为了实现流式调用而让方法返回this

var buffer = StringBuffer()
  ..write('one')
  ..write('two')
  ..write('three');

Dart延迟运行

Future.delayed(
  const Duration(seconds: 5),
  () => {
    print('delay 5s run');
  });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment