Search code examples
javafluttervariablesnaming

How to Insert For In Loop Variable into Variable Call


    class GraphData {
    List <double> closingPricesBTC = [];
    List <double> closingPricesETH = [];
    List <double> closingPricesLTC = [];

        for (String cryptoCurrency in cryptoAbbreviation){
        .
        . (some code)
        .
        double closePrice = ....

        closingPrices.add(closePrice);
        }

}

where cryptoAbbreviation is

const List<String> cryptoAbbreviation = ['BTC', 'ETH', 'LTC'];

How can I append the current "cryptocurrency" String into the name of the variable for closingPrices.add(closePrice) so that I can end up with closingPricesBTC.add(closePrice), closingPricesETH.add(closePrice), and closingPricesLTC.add(closePrice)

I've tried closingPrices$cryptoCurrency.add(closePrice); but that doesn't work.


Solution

  • You can't generate variable names but you can try HashMap(Java)/Map(Dart). This should fulfill your requirement.

    Map<String, List<double>> closingPrices = {'BTC':[], 'ETH':[], 'LTC':[]};
    
    
            for (String cryptoCurrency in cryptoAbbreviation){
            .
            . (some code)
            .
            double closePrice = ....
    
            closingPrices[cryptoCurrency].add(closePrice);
            }