Home > OS >  How to invoke/reference Map/dictionaries before its initalized in dart?
How to invoke/reference Map/dictionaries before its initalized in dart?

Time:09-28

account(initial_balance) {
  deposit(amount) {
    dispatch['balance']  = amount; //error message on dispatch here.
    return dispatch['balance'];//error message on dispatch here.
  }

  withdraw(amount) {
    if (amount > dispatch['balance']) { //error message on dispatch here.
      return 'Insufficient funds';
    }
    dispatch['balance'] -= amount;//error message on dispatch here.
    return dispatch['balance'];//error message on dispatch here.
  }

  var dispatch = {
    'deposit': deposit,
    'withdraw': withdraw,
    'balance': initial_balance
  };
  return dispatch;
}

withdraw(account, amount) {
  return account['withdraw'](amount);
}

deposit(account, amount) {
  return account['deposit'](amount);
}

check_balance(account) {
  return account['balance'];
}

I translated this code from python dictionaries, But in dart i am getting the following error

"Local variable dispatch cannot be referenced before it is declared.Try renaming/moving the declaration before first use so that it doesn't hide a name from enclosing scope"

Any ideas on what is causing this type of error and how i can use dictionary without having to declare it before the functions? The code works in python where i can declare dictionary in the last part of the function.

CodePudding user response:

As the error message says, dispatch must be declared before it is referenced. You can declare dispatch separately (either as an empty Map or as a late variable) before defining the local functions, and you then can add those references later.

Map<String, dynamic> account(dynamic initial_balance) {
  late Map<String, dynamic> dispatch;
  
  dynamic deposit(dynamic amount) {
    dispatch['balance']  = amount;
    return dispatch['balance'];
  }

  dynamic withdraw(dynamic amount) {
    if (amount > dispatch['balance']) {
      return 'Insufficient funds';
    }
    dispatch['balance'] -= amount;
    return dispatch['balance'];
  }

  dispatch = <String, dynamic>{
    'deposit': deposit,
    'withdraw': withdraw,
    'balance': initial_balance
  };
  return dispatch;
}
  • Related