在此示例中,您不需要多行来计算值。你可以这样做:
Example(String json) : this.tasks = jsonDecode(json);
在您确实需要多个语句的更一般情况下,如果字段初始化值不相关,我会为每个语句使用辅助函数:
Example(String json) : this.tasks = _computeTasks(json);
static List<String> _computeTasks(String json) {
List<String> result;
// compute compute compute
return result;
}
如果您有多个字段需要使用来自同一计算的值进行初始化,我会首先尝试将其设为工厂构造函数:
final Something somethingElse;
Example._(this.tasks, this.somethingElse);
factory Example(String json) {
List<String> tasks;
Something somethingElse;
// compute compute compute
return Example._(tasks, somethingElse);
}
如果构造函数需要是生成的,并且你需要在同一个计算中计算多个值,并且不改变这一点非常重要,那么我会可能会创建一个包含这些值的中间对象:
Example(String json) : this._(_computeValues(json));
Example._(_Intermediate values)
: tasks = values.tasks, somethingElse = values.somethingElse;
static _Intermediate _computeValues(String json) {
List<String> tasks;
Something somethingElse;
// compute compute compute
return _Intermediate(tasks, somethingElse);
}
...
}
// Helper class.
class _Intermediate {
final List<String> tasks;
final Something somethingElse;
_Intermediate(this.tasks, this.somethingElse);
}
如果类型相同,您也许可以使用List 代替中间值的辅助类。或者,您也许可以重用像
这样的类
class Pair<S, T> {
final S first;
final T second;
Pair(this.first, this.second);
}
你怎么做并不是很重要,用户永远看不到中间值。