1

How can this list of map objects be refactored for better reading?

The goal is to have a list variable that stores the x and y values for a couple of points in a compact way. It does not have to be a list of map objects, I just found it the most suitable at the time of writing.

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
  }
];

2 Answers 2

2
    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]
     };
  });
Sign up to request clarification or add additional context in comments.

2 Comments

You should provide some explanation for this code as well.
Thanks, that helps. Is even an easier way in Dart to make such an ordered set of tuples?
1

The answer of @Axot is good. I think you might want to improve on the stored data structure as well. If you are storing coordinates, maybe just create a Point 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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.