You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中AccountModel初始化空transactions数组报错求助

问题解决:Dart构造函数中初始化空数组报错

错误原因

Dart禁止将可变对象(比如[]、{})作为可选命名参数的默认值——所有类实例会共享同一个可变对象,后续修改数组时会影响所有AccountModel实例的transactions属性,引发意外的状态混乱。

解决方法

方法一:初始化列表处理(通用推荐)

把transactions参数设为可空类型,在构造函数的初始化列表中用空数组兜底,确保每个实例拥有独立的空数组:

class AccountModel {
  String id;
  String name;
  DateTime createdOn;
  List<TransactionModel> transactions;
  bool isLocked;
  double payTotal;
  double receiveTotal;
  double balance;
  TransactionModel? lastEntry;

  AccountModel({
    required this.id,
    required this.name,
    required this.createdOn,
    List<TransactionModel>? transactions,
    this.isLocked = false,
    this.balance = 0,
    this.lastEntry,
    this.payTotal = 0,
    this.receiveTotal = 0,
  }) : transactions = transactions ?? [];
}

方法二:const空数组(限特定场景)

如果TransactionModel是不可变类(拥有const构造函数),可以用const []作为默认值——const对象不可变且共享,不会出现状态修改问题:

class AccountModel {
  String id;
  String name;
  DateTime createdOn;
  List<TransactionModel> transactions;
  bool isLocked;
  double payTotal;
  double receiveTotal;
  double balance;
  TransactionModel? lastEntry;

  AccountModel({
    required this.id,
    required this.name,
    required this.createdOn,
    this.transactions = const [],
    this.isLocked = false,
    this.balance = 0,
    this.lastEntry,
    this.payTotal = 0,
    this.receiveTotal = 0,
  });
}

内容的提问来源于stack exchange,提问作者Irfan Ganatra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 09:33:02