【问题标题】:Storing Data in Map Lists is Including Data from Previous List. Flutter将数据存储在地图列表中是包括来自先前列表的数据。扑
【发布时间】:2021-02-27 06:14:52
【问题描述】:

我的数据在 cryptoSpots 地图中的存储方式存在问题。我在 build 方法中调用了 getSpotData 方法 3 次,每次都使用不同的传递字符串,如下所示:

        getSpotData('BTC');
        getSpotData('ETH');
        getSpotData('LTC');

问题在于,当我第二次调用 getSpotData getSpotData('ETH') 和第三次调用 getSpotData('LTC') 时,cryptoSpots 映射内的列表中存储的值包括它之前列表中的数据。

例如,我希望数据是:

Map<String, List<FlSpot>> cryptoSpots = {
                    'BTC': [1, 2, 3],
                    'ETH': [4, 5, 6],
                    'LTC': [7, 8, 9],
                  };

但我得到的是:

Map<String, List<FlSpot>> cryptoSpots = {
                        'BTC': [1, 2, 3],
                        'ETH': [1, 2, 3, 4, 5, 6],
                        'LTC': [1, 2, 3, 4, 5, 6, 7, 8, 9],
                      };

 class Graph extends StatefulWidget {
          Graph(this.closingTimesAndPrices);
        
          final Map<String, List<dynamic>> closingTimesAndPrices;
        
          @override
          _GraphState createState() => _GraphState();
        }    
        
        class _GraphState extends State<Graph> {
              Map<String, List<FlSpot>> cryptoSpots = {
                'BTC': [],
                'ETH': [],
                'LTC': [],
              };
        
          List<double> doubleList = [];
        
          @override
          void initState() {
            super.initState();
          }
        
          getSpotData(String crypto) {
    
            // Extracting price values from Map for passed crypto and reversing it
            List<String> stringSpotsList =
                widget.closingTimesAndPrices[crypto].reversed.toList();
        
            //converting String List to Double List
            for (int j = 0; j < stringSpotsList.length; j++) {
              var doubleData = double.parse(stringSpotsList[j]);
              doubleList.add(doubleData);
            }
        
            cryptoSpots[crypto] = doubleList.asMap().entries.map((e) {
              return FlSpot(e.key.toDouble(), e.value);
            }).toList();
        
            return cryptoSpots[crypto];
          }
    }

@override
  Widget build(BuildContext context) {
...(some code)...
    
        getSpotData('BTC');
        getSpotData('ETH');
        getSpotData('LTC');

}

【问题讨论】:

    标签: list flutter


    【解决方案1】:

    问题在于您的 doubleList 数组。每次调用 getSpotData 方法时,您都将项目添加到此数组中。这就是将以前称为加密货币的值添加到当前值的原因。除了全局 doubleList 变量,您可以在函数范围内定义另一个变量,或者您可以在 getSpotData 函数调用期间清除 doubleList 数组。

    ...
    doubleList = [];
    for (int j = 0; j < stringSpotsList.length; j++) {
              var doubleData = double.parse(stringSpotsList[j]);
              doubleList.add(doubleData);
    }
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-21
      • 2021-06-25
      • 2011-03-05
      相关资源
      最近更新 更多