[英]Refactoring a list of map objects in Dart?
如何重構這個 map 對象列表以便更好地閱讀?
目標是有一個列表變量,它以緊湊的方式存儲幾個點的 x 和 y 值。 它不一定是 map 對象的列表,我只是在撰寫本文時發現它最合適。
final List<Map<String, double>> _positions = [
{
'x': _offsetCircle + _circleDistanceHorizontal * 1,
'y': _height * 0.120
},
{
'x': _offsetCircle + _circleDistanceHorizontal * 2,
'y': _height * 0.075
},
{
'x': _offsetCircle + _circleDistanceHorizontal * 3,
'y': _height * 0.095
},
{
'x': _offsetCircle + _circleDistanceHorizontal * 4,
'y': _height * 0.070
},
{
'x': _offsetCircle + _circleDistanceHorizontal * 5,
'y': _height * 0.085
},
{
'x': _offsetCircle + _circleDistanceHorizontal * 6,
'y': _height * 0.055
},
{
'x': _offsetCircle + _circleDistanceHorizontal * 7,
'y': _height * 0.060
},
{
'x': _offsetCircle + _circleDistanceHorizontal * 8,
'y': _height * 0.060
},
{
'x': _offsetCircle + _circleDistanceHorizontal * 9,
'y': _height * 0.045
},
{
'x': _offsetCircle + _circleDistanceHorizontal * 10,
'y': _height * 0.025
},
{
'x': _offsetCircle + _circleDistanceHorizontal * 11,
'y': _height * 0.04
},
{
'x': _offsetCircle + _circleDistanceHorizontal * 12,
'y': _height * 0.005
}
];
final items = [0.12, 0.075, 0.095];
List<Map<String, double>> result = List<Map<String, double>>.generate(items.length ,(index) {
return {
'x': _offsetCircle + _circleDistanceHorizontal * (index + 1),
'y':_height * items[index]
};
});
@Axot 的答案很好。 我認為您可能還想改進存儲的數據結構。 如果您要存儲坐標,也許只需創建一個點 class。
class Point {
final double x;
final double y;
Point(this.x, this.y);
}
double _offsetCircle = 1.0, _circleDistanceHorizontal = 1.0;
double _height = 1.0;
final factors = [0.120, 0.075, 0.095];
final list = Iterable<int>.generate(factors.length)
.map((i) => Point(_offsetCircle + _circleDistanceHorizontal * (i + 1),
_height * factors[i]))
.toList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.