flutter开发技术:基础语法

79 阅读1分钟

背景: 提高代码的整洁性

  1. ??= 的使用

不建议的写法

String get fullName {
  if (_fullName == null) {
    _fullName = getFullUserName(this);
  }
  return _fullName;
}

建议的写法

String get fullName {
  return _fullName ??= getFullUserName(this);
}

2.避免使用forEach for循环使开发人员能够清楚明确地表达他们的意图。for循环体中的返回是从函数体返回,而forEach闭包体中的返回只返回forEach迭代的值。for循环的闭包体可以包含await,而forEach的闭包体不可以。

不建议写法

people.forEach((person) {
  ...
});

建议的写法

for (var person in people) {
  ...
}

3.用 nil 代替 const Container ()

当您不想显示任何内容时,在 widgets 树中添加一个简单的 widgets,对性能的影响最小。

text != null ? Text(text) : const Container() 
text != null ? Text(text) : const SizedBox()
//base
text != null ? Text(text) : nil 
or 
if (text != null) Text(text)

4.??的使用

不建议的写法

var car = van == null ? bus : audi; 

建议的写法

var car = audi ?? bus;   

5.?.的使用 不建议的写法

var car = van == null ? null : audi.bus;

建议的写法

var car = audi?.bus;