首页 > 解决方案 > Dart 类构造函数初始化构造函数主体中的字段

问题描述

我正在尝试在以下代码中初始化现场任务,但出现错误:Non-nullable instance field 'tasks' must be initialized.. Example(this.tasks) {}我可以使用类似or的语法成功初始化字段,Example(String json) : this.tasks = [json]但是当我需要使用多行来计算下面代码中的值时,我不确定如何初始化字段。

import 'dart:convert';

class Example {
  List<String> tasks;
  Example(String json) {
    List<String> data = jsonDecode(json);
    this.tasks = data;
  }
}

标签: classdartconstructor

解决方案


在此示例中,您不需要多行来计算该值。你可以这样做:

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);
}

如果类型相同,您也许可以使用 aList而不是辅助类作为中间值。或者,您也许可以重用类似的类

class Pair<S, T> { 
  final S first; 
  final T second; 
  Pair(this.first, this.second);
}

你怎么做并不是很重要,用户永远不会看到中间值。


推荐阅读