我想根据另一个参数的值在构造函数中初始化一个参数。

因此,根据 oldEmployee 是否不为空,我应将其添加到 availableEmployees 列表中,否则将availableEmployees列表保持原样。

我想在此类中执行此操作的原因是,我已阅读到,使用Bloc时,我应该在Bloc的状态内进行计算,而不是在UI中执行此操作。

这是我的类(class)样子:

class ShiftCreatedOrEdited extends ShiftsState {
  final List<Employee> availableEmployees;
  final Employee oldEmployee;

  const ShiftCreatedOrEdited({
    this.availableEmployees,
    this.oldEmployee,
  });

  List<Employee> addOldEmployeeToTheAvailableEmployees(List<Employee> availableEmployees, Employee oldEmployee) {
    if (oldEmployee != null) {
      List<Employee> hList = availableEmployees;
      hList.add(oldEmployee);
      return hList;
    } else {
      return availableEmployees;
    }
  }
}

最佳答案

这个怎么样:

void main() {}

class Employee {}

class ShiftsState {}

class ShiftCreatedOrEdited {
  final Employee oldEmployee;
  final List<Employee> availableEmployees;

  ShiftCreatedOrEdited(
      Employee _oldEmployee, List<Employee> _availableEmployees)
      : this.availableEmployees =
            _availableEmployees + (_oldEmployee != null ? [_oldEmployee] : []),
        this.oldEmployee = _oldEmployee;
}

08-18 18:21