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
相关产品推荐
相关产品推荐

