Skip to content

Commit

Permalink
Center Floating Snackbar with custom width when direction is RTL (#14…
Browse files Browse the repository at this point in the history
…0215)

## Description

This PR fixes the positionning of a floating snackbar when the text direction is RTL.

## Related Issue

Fixes flutter/flutter#140125.

## Tests

Adds 1 test.
  • Loading branch information
bleroux authored Dec 16, 2023
1 parent c1e207d commit 596d9b6
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
8 changes: 7 additions & 1 deletion packages/flutter/lib/src/material/scaffold.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1183,7 +1183,13 @@ class _ScaffoldLayout extends MultiChildLayoutDelegate {
: contentBottom;
}

final double xOffset = hasCustomWidth ? (size.width - snackBarWidth!) / 2 : 0.0;
double xOffset = 0.0;
if (hasCustomWidth) {
xOffset = switch (textDirection) {
TextDirection.rtl => (snackBarWidth! - size.width) / 2,
TextDirection.ltr => (size.width - snackBarWidth!) / 2,
};
}
positionChild(_ScaffoldSlot.snackBar, Offset(xOffset, snackBarYOffsetBase - snackBarSize.height));

assert((){
Expand Down
43 changes: 43 additions & 0 deletions packages/flutter/test/material/snack_bar_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2604,6 +2604,49 @@ void main() {
expect(snackBarTopRight.dx - actionTopRight.dx, 8.0 + 15.0); // button margin + horizontal scaffold outside margin
},
);

testWidgets('Floating snackbar with custom width is centered when text direction is rtl', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/140125.
const double customWidth = 400.0;
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: TextDirection.rtl,
child: Scaffold(
body: Builder(
builder: (BuildContext context) {
return GestureDetector(
onTap: () {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
behavior: SnackBarBehavior.floating,
width: customWidth,
content: Text('Feeling super snackish'),
),
);
},
child: const Text('X'),
);
},
),
),
),
),
);

await tester.tap(find.text('X'));
await tester.pump(); // start animation
await tester.pump(const Duration(milliseconds: 750));

final Finder materialFinder = find.descendant(
of: find.byType(SnackBar),
matching: find.byType(Material),
);
final Offset snackBarBottomLeft = tester.getBottomLeft(materialFinder);
final Offset snackBarBottomRight = tester.getBottomRight(materialFinder);
expect(snackBarBottomLeft.dx, (800 - customWidth) / 2); // Device width is 800.
expect(snackBarBottomRight.dx, (800 + customWidth) / 2); // Device width is 800.
});
});

testWidgets('SnackBars hero across transitions when using ScaffoldMessenger', (WidgetTester tester) async {
Expand Down

0 comments on commit 596d9b6

Please sign in to comment.