Skip to content

Commit

Permalink
Add RelativeRect.fromDirectional factory (flutter#107059)
Browse files Browse the repository at this point in the history
Add `fromDirectional` factory to `RelativeRect` for when an app needs to consider both TextDirection.ltr and TextDirection.rtl.

```
RelativeRect.fromDirectional(
    textDirection: textDirection,
    start: 10.0,
    top: 20.0,
    end: 30.0,
    bottom: 40.0,
);
```

Addresses flutter#107058.
  • Loading branch information
kseino authored and camsim99 committed Aug 10, 2022
1 parent 786961e commit a098528
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
31 changes: 31 additions & 0 deletions packages/flutter/lib/src/rendering/stack.dart
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,37 @@ class RelativeRect {
);
}

/// Creates a RelativeRect from horizontal position using `start` and `end`
/// rather than `left` and `right`.
///
/// If `textDirection` is [TextDirection.rtl], then the `start` argument is
/// used for the [right] property and the `end` argument is used for the
/// [left] property. Otherwise, if `textDirection` is [TextDirection.ltr],
/// then the `start` argument is used for the [left] property and the `end`
/// argument is used for the [right] property.
factory RelativeRect.fromDirectional({
required TextDirection textDirection,
required double start,
required double top,
required double end,
required double bottom,
}) {
double left;
double right;
switch (textDirection) {
case TextDirection.rtl:
left = end;
right = start;
break;
case TextDirection.ltr:
left = start;
right = end;
break;
}

return RelativeRect.fromLTRB(left, top, right, bottom);
}

/// A rect that covers the entire container.
static const RelativeRect fill = RelativeRect.fromLTRB(0.0, 0.0, 0.0, 0.0);

Expand Down
18 changes: 18 additions & 0 deletions packages/flutter/test/rendering/relative_rect_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,24 @@ void main() {
const RelativeRect r = RelativeRect.fromLTRB(10.0, 20.0, 30.0, 40.0);
expect(r, RelativeRect.fromSize(const Rect.fromLTWH(10.0, 20.0, 0.0, 0.0), const Size(40.0, 60.0)));
});
test('RelativeRect.fromDirectional', () {
final RelativeRect r1 = RelativeRect.fromDirectional(
textDirection: TextDirection.ltr,
start: 10.0,
top: 20.0,
end: 30.0,
bottom: 40.0,
);
final RelativeRect r2 = RelativeRect.fromDirectional(
textDirection: TextDirection.rtl,
start: 10.0,
top: 20.0,
end: 30.0,
bottom: 40.0,
);
expect(r1, const RelativeRect.fromLTRB(10.0, 20.0, 30.0, 40.0));
expect(r2, const RelativeRect.fromLTRB(30.0, 20.0, 10.0, 40.0));
});
test('RelativeRect.shift', () {
const RelativeRect r1 = RelativeRect.fromLTRB(10.0, 20.0, 30.0, 40.0);
final RelativeRect r2 = r1.shift(const Offset(5.0, 50.0));
Expand Down

0 comments on commit a098528

Please sign in to comment.