首页 > 解决方案 > DART 中类字段的默认值

问题描述

我知道这是一个愚蠢的问题,但我已经坚持了很长一段时间了。

如何在 DART 中设置类成员的默认值。这就是我提供成员默认值的方式,但它始终为null

如果在构造函数中提供了这些值,那么它应该使用这些值,否则使用默认值。

class BillingInfoDetails {
  bool billToClient = false;
  String clientName = "";
  String reasonOfTravel = "";
  String remarks = "";

  BillingInfoDetails({
    this.billToClient,
    this.clientName,
    this.reasonOfTravel,
    this.remarks,
  });
}

标签: oopdartconstructor

解决方案


像这样:

class BillingInfoDetails {
  bool billToClient;
  String clientName;
  String reasonOfTravel;
  String remarks;

  BillingInfoDetails({
    this.billToClient = false,
    this.clientName = "",
    this.reasonOfTravel = "",
    this.remarks = "",
  });
}

您可以在 Dart 指南中找到此信息:https ://dart.dev/guides/language/language-tour#parameters在“默认参数值”部分。


推荐阅读