There is indeed no built-in way to do this.
Since the list keeps the same length, the most efficient approach would move the elements in-place rather than remove an element and then insert it again. The latter requires moving all later elements as well, where doing it in-place only requires moving the elements between from
and to
.
Example:
extension MoveElement<T> on List<T> {
void move(T element, int offset) {
var from = indexOf(element);
if (from < 0) return; // Or throw, whatever you want.
var to = from + offset;
// Check to position is valid. Or cap it at 0/length - 1.
RangeError.checkValidIndex(to, this, "target position", length);
element = this[from];
if (from < to) {
this.setRange(from, to, this, from + 1);
} else {
this.setRange(to + 1, from + 1, this, to);
}
this[to] = element;
}
}
I would probably prefer a more general "move" function like:
extension MoveElement<T> on List<T> {
void move(int from, int to) {
RangeError.checkValidIndex(from, this, "from", length);
RangeError.checkValidIndex(to, this, "to", length);
var element = this[from];
if (from < to) {
this.setRange(from, to, this, from + 1);
} else {
this.setRange(to + 1, from + 1, this, to);
}
this[to] = element;
}
}
and then build the "find element, then move it relative to where it was" on top of that.