【问题标题】:Dart Flutter: The default value of an optional parameter must be constant when setting a default value to class constructorDart Flutter:为类构造函数设置默认值时,可选参数的默认值必须是常量
【发布时间】:2020-09-06 07:10:29
【问题描述】:

我创建了一个类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 flutter dart default-value


    【解决方案1】:

    您不能在类模型中初始化对象。

    试试:

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

    【讨论】:

    • 谢谢,我很困惑,因为有太多的方法可以写同样的东西。第一个解决方案有效,你能解释一下第一个语法吗?这里冒号:是什么意思和用法?
    • 构造函数后面的冒号在 Flutter 中称为初始化列表。它允许您初始化类的字段,进行断言并调用超级构造函数。如果你想了解更多:dart.dev/guides/language/language-tour#initializer-list
    【解决方案2】:

    试试这个可能吗?

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

    【讨论】:

      猜你喜欢
      • 2020-09-09
      • 1970-01-01
      • 2021-12-25
      • 1970-01-01
      • 2020-12-31
      • 1970-01-01
      • 1970-01-01
      • 2016-11-03
      相关资源
      最近更新 更多