skip to Main Content

I have created a model class for account of person, where i want to assing transactions to empty array..

i have assigned like this.transactions=[],

here is my modelclass


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,
  this.transactions= [],// this is showing an error


 this.isLocked=false,
        this.balance=0,
        required this.createdOn,
        this.lastEntry,
        this.payTotal=0,
        this.receiveTotal=0,

      });


}

2

Answers


  1. Here is List<TransactionModel> transactions;. Not dynamic type. You assigned with dynamic empty list. Can initialize with TransactionModel object.

    Login or Signup to reply.
  2. The error says exactly what’s wrong.

    The default value of an optional parameter must be constant.
    

    To solve make it a constant by writing const in front of it:

    this.transactions = const []
    

    EDIT:

    As you have found out, a const list is unmodifiable so it’s not really desired to have. I see two options to solve this. The first is to not make it part of the constructor at all and always initialize it with [] so like

    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,
        this.isLocked = false,
        this.balance = 0,
        required this.createdOn,
        this.lastEntry,
        this.payTotal = 0,
        this.receiveTotal = 0,
      });
    }
    

    If you really need it to be part of the constructor maybe this work around works for you:

    class AccountModel {
      String id;
      String name;
      DateTime createdOn;
      List<TransactionModel> _transactions = [];
      List<TransactionModel> get transactions => _transactions;
      set transactions(value) => _transactions = value;
      bool isLocked;
      double payTotal;
      double receiveTotal;
      double balance;
      TransactionModel? lastEntry;
    
      AccountModel({
        required this.id,
        required this.name,
        List<TransactionModel>? transactions,
        this.isLocked = false,
        this.balance = 0,
        required this.createdOn,
        this.lastEntry,
        this.payTotal = 0,
        this.receiveTotal = 0,
      }) {
        if (transactions != null) _transactions = transactions;
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search