簡體   English   中英

Dart Flutter:為類構造函數設置默認值時,可選參數的默認值必須是常量

[英]Dart Flutter: The default value of an optional parameter must be constant when setting a default value to class constructor

我創建了一個類JobBloc ,其中包含許多屬性,其中一個是另一個類對象JobModel ,我想為這些屬性中的每一個分配一個默認值,除了JobModel屬性外,它工作正常:

class JobBloc with JobModelFormValidator {
  final JobModel jobModel;
  final bool isValid;
  final bool showErrorMessage;
  final String name;
  final double ratePerHour;
  final bool enableForm;
  final bool showIcon;

  JobBloc({
    // The default value of an optional parameter must be constant.
    this.jobModel = JobModel(name: 'EMPTY', ratePerHour: 0.01), // <= the error stems from this line
    this.isValid = false,
    this.showErrorMessage = false,
    this.name = 'EMPTY',
    this.enableForm = true,
    this.ratePerHour = 0.01,
    this.showIcon = false,
    });
}

如何為我的jobModel屬性分配默認值?

您不能在類模型中初始化對象。

嘗試:

class JobBloc with JobModelFormValidator {
  final JobModel jobModel;
  final bool isValid;
  final bool showErrorMessage;
  final String name;
  final double ratePerHour;
  final bool enableForm;
  final bool showIcon;

  JobBloc({
    this.isValid = false,
    this.showErrorMessage = false,
    this.name = 'EMPTY',
    this.enableForm = true,
    this.ratePerHour = 0.01,
    this.showIcon = false,
    }) : jobModel = JobModel(name: 'EMPTY', ratePerHour: 0.01);
}

或者更新 jobModel 類

class JobModel {
  final String name;
  final double ratePerHour;

  JobModel({
    this.name = 'EMPTY',
    this.ratePerHour = 0.01,
  });
}

試試這個可能是?

class JobBloc with JobModelFormValidator {
  final JobModel jobModel;
  final bool isValid;
  final bool showErrorMessage;
  final String name;
  final double ratePerHour;
  final bool enableForm;
  final bool showIcon;

  JobBloc({
    this.jobModel = const JobModel(name: 'EMPTY', ratePerHour: 0.01),
    this.isValid = false,
    this.showErrorMessage = false,
    this.name = 'EMPTY',
    this.enableForm = true,
    this.ratePerHour = 0.01,
    this.showIcon = false,
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM