Skip to content

Commit 8f190aa

Browse files
authored
[material_ui] Add the Material shapes. (flutter#12771)
## Description Adds the Material shapes library to `material_ui`, a Dart port of the AndroidX [graphics-shapes](https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:graphics/graphics-shapes/) library and the Compose [MaterialShapes](https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/MaterialShapes.kt) catalog. These APIs are the foundation for upcoming M3 Expressive components (loading indicator, wavy progress indicators, etc.) and let app developers use the Material shape catalog and shape-morphing animations directly. New public API: - `RoundedPolygon`, `CornerRounding`: creation and normalization of rounded polygonal shapes. - `MaterialShapes`: the catalog of 35 predefined Material Design shapes (pictured below). - `MaterialShapeBorder`: an `OutlinedBorder` that draws a `RoundedPolygon`, so the shapes plug into the existing `ShapeDecoration`/`shape` APIs and morph between each other through the usual border lerping. The port keeps the geometry and behavior of the Kotlin original (unit tests are ported from AndroidX alongside new ones), while adapting the API surface to Dart/Flutter conventions. Every shape in `MaterialShapes.all` is covered by a golden test. Also includes a new example that morphs through the whole catalog. Closes flutter/flutter#184934 ## Shapes catalog <img width="650" alt="material_shapes" src="https://github.com/user-attachments/assets/8cf73820-321e-40fb-b8b3-29f6a697ebb3" /> ## Example https://github.com/user-attachments/assets/293fe53d-2ee2-4095-9446-694efdca4c04 ## Pre-Review Checklist **Note**: The Flutter team is currently trialing the use of [Gemini Code Assist for GitHub](https://developers.google.com/gemini-code-assist/docs/review-github-code). Comments from the `gemini-code-assist` bot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed. [^1]: Regular contributors who have demonstrated familiarity with the repository guidelines only need to comment if the PR is not auto-exempted by repo tooling.
1 parent 5909913 commit 8f190aa

32 files changed

Lines changed: 7409 additions & 0 deletions

‎packages/material_ui/example/lib/main.dart‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import 'progress_indicator/linear_progress_indicator.0.dart'
2828
import 'progress_indicator/circular_progress_indicator.0.dart'
2929
as circular_progress_indicator_0;
3030
import 'dropdown_menu/dropdown_menu.1.dart' as dropdown_menu_1;
31+
import 'material_shapes/material_shapes.0.dart' as material_shapes_0;
3132
import 'navigation_bar/navigation_bar.1.dart' as navigation_bar_1;
3233
import 'navigation_rail/navigation_rail.0.dart' as navigation_rail_0;
3334
import 'navigation_drawer/navigation_drawer.0.dart' as navigation_drawer_0;
@@ -161,6 +162,12 @@ class ExampleApp extends StatelessWidget {
161162
builder: (BuildContext context) =>
162163
const circular_progress_indicator_0.ProgressIndicatorExampleApp(),
163164
),
165+
_Example(
166+
filepath: 'material_shapes/material_shapes.0.dart',
167+
title: 'Material 3 Expressive shapes',
168+
builder: (BuildContext context) =>
169+
const material_shapes_0.MaterialShapesExampleApp(),
170+
),
164171
_Example(
165172
filepath: 'dropdown_menu/dropdown_menu.1.dart',
166173
title: 'Menu',
Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
// Copyright 2013 The Flutter Authors
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
// #region body
6+
import 'dart:async';
7+
8+
import 'package:flutter/physics.dart';
9+
import 'package:material_ui/material_ui.dart';
10+
11+
/// Flutter code sample for [MaterialShapes].
12+
13+
void main() {
14+
runApp(const MaterialShapesExampleApp());
15+
}
16+
17+
class MaterialShapesExampleApp extends StatelessWidget {
18+
const MaterialShapesExampleApp({super.key});
19+
20+
@override
21+
Widget build(BuildContext context) {
22+
return MaterialApp(home: const MaterialShapesExample());
23+
}
24+
}
25+
26+
class MaterialShapesExample extends StatefulWidget {
27+
const MaterialShapesExample({super.key});
28+
29+
@override
30+
State<MaterialShapesExample> createState() => _MaterialShapesExampleState();
31+
}
32+
33+
class _MaterialShapesExampleState extends State<MaterialShapesExample>
34+
with SingleTickerProviderStateMixin {
35+
/// The shapes to morph through, in the order they are listed in
36+
/// [MaterialShapes.all].
37+
static final List<RoundedPolygon> _shapes = MaterialShapes.all;
38+
39+
/// A tween from each shape in [_shapes] to the next one, wrapping around
40+
/// from the last shape back to the first.
41+
///
42+
/// Lerping between two [MaterialShapeBorder]s morphs one shape into the
43+
/// other.
44+
late final List<ShapeBorderTween> _tweens;
45+
46+
/// The tween that is currently animating.
47+
late ShapeBorderTween _tween;
48+
49+
/// Drives the progress of [_tween].
50+
///
51+
/// The controller is unbounded so that the springs below can overshoot past a
52+
/// progress of 1, which carries the morph slightly beyond its end shape.
53+
late final AnimationController _controller;
54+
55+
int _morphIndex = 0;
56+
57+
Timer? _startTimer;
58+
59+
final _bouncySimulation = SpringSimulation(
60+
SpringDescription.withDampingRatio(ratio: 0.5, stiffness: 400, mass: 1),
61+
0,
62+
1,
63+
5,
64+
snapToEnd: true,
65+
);
66+
67+
// Overshooting past a progress of 1 extrapolates a morph beyond its end
68+
// shape, which distorts the heart into sharp spikes. The heart therefore
69+
// animates with a spring that starts at rest and barely overshoots.
70+
final _lessBouncySimulation = SpringSimulation(
71+
SpringDescription.withDampingRatio(ratio: 0.8, stiffness: 300, mass: 1),
72+
0,
73+
1,
74+
0,
75+
snapToEnd: true,
76+
);
77+
78+
/// The shape that the currently animating morph ends on.
79+
RoundedPolygon get _targetShape =>
80+
_shapes[(_morphIndex + 1) % _shapes.length];
81+
82+
@override
83+
void initState() {
84+
super.initState();
85+
86+
_tweens = <ShapeBorderTween>[
87+
for (var i = 0; i < _shapes.length; i++)
88+
ShapeBorderTween(
89+
begin: MaterialShapeBorder(shape: _shapes[i]),
90+
end: MaterialShapeBorder(shape: _shapes[(i + 1) % _shapes.length]),
91+
),
92+
];
93+
_tween = _tweens.first;
94+
_controller = AnimationController.unbounded(vsync: this);
95+
96+
// Hold the first shape for a moment so that it can be seen before it starts
97+
// morphing.
98+
_startTimer = Timer(const Duration(seconds: 1), _morphThroughShapes);
99+
}
100+
101+
@override
102+
void dispose() {
103+
_startTimer?.cancel();
104+
_controller.dispose();
105+
super.dispose();
106+
}
107+
108+
/// Animates the tweens in [_tweens] one after another, looping back to the
109+
/// first one after the last, until this widget is disposed.
110+
///
111+
/// Waiting for each spring to settle, rather than advancing on a fixed
112+
/// interval, keeps a morph from being cut short and popping to the next
113+
/// shape.
114+
Future<void> _morphThroughShapes() async {
115+
while (mounted) {
116+
setState(() => _tween = _tweens[_morphIndex]);
117+
_controller.value = 0;
118+
await _controller.animateWith(
119+
_targetShape == MaterialShapes.heart
120+
? _lessBouncySimulation
121+
: _bouncySimulation,
122+
);
123+
_morphIndex = (_morphIndex + 1) % _tweens.length;
124+
}
125+
}
126+
127+
@override
128+
Widget build(BuildContext context) {
129+
return Scaffold(
130+
appBar: AppBar(title: const Text('Material 3 Expressive Shapes Sample')),
131+
body: Center(
132+
child: ConstrainedBox(
133+
constraints: const BoxConstraints(maxWidth: 300, maxHeight: 300),
134+
child: AspectRatio(
135+
aspectRatio: 1,
136+
child: AnimatedBuilder(
137+
animation: _controller,
138+
builder: (BuildContext context, Widget? child) {
139+
return DecoratedBox(
140+
decoration: ShapeDecoration(
141+
color: Theme.of(context).colorScheme.primary,
142+
shape: _tween.evaluate(_controller)!,
143+
),
144+
);
145+
},
146+
),
147+
),
148+
),
149+
),
150+
);
151+
}
152+
}
153+
// #endregion body

‎packages/material_ui/example/test/main_test.dart‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@ import 'package:material_ui_examples/progress_indicator/circular_progress_indica
4242
as circular_progress_indicator_0;
4343
import 'package:material_ui_examples/dropdown_menu/dropdown_menu.1.dart'
4444
as dropdown_menu_1;
45+
import 'package:material_ui_examples/material_shapes/material_shapes.0.dart'
46+
as material_shapes_0;
4547
import 'package:material_ui_examples/navigation_bar/navigation_bar.1.dart'
4648
as navigation_bar_1;
4749
import 'package:material_ui_examples/navigation_rail/navigation_rail.0.dart'
@@ -87,6 +89,7 @@ const Map<String, Type> _examples = <String, Type>{
8789
linear_progress_indicator_0.ProgressIndicatorExampleApp,
8890
'Circular progress indicators':
8991
circular_progress_indicator_0.ProgressIndicatorExampleApp,
92+
'Material 3 Expressive shapes': material_shapes_0.MaterialShapesExampleApp,
9093
'Menu': dropdown_menu_1.DropdownMenuApp,
9194
'Navigation bar': navigation_bar_1.NavigationBarApp,
9295
'Navigation rail': navigation_rail_0.NavigationRailExampleApp,
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
// Copyright 2013 The Flutter Authors
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
import 'package:flutter_test/flutter_test.dart';
6+
import 'package:material_ui/material_ui.dart';
7+
import 'package:material_ui_examples/material_shapes/material_shapes.0.dart'
8+
as example;
9+
10+
void main() {
11+
/// Comfortably longer than it takes either of the example's springs to
12+
/// settle.
13+
const Duration morphDuration = Duration(seconds: 3);
14+
15+
/// The side of the square the example paints its shape in.
16+
const side = 300.0;
17+
18+
/// Scales [points] from the unit square up to the painted square.
19+
List<Offset> scaled(List<Offset> points) {
20+
return <Offset>[for (final Offset point in points) point * side];
21+
}
22+
23+
/// Samples points on a grid over the unit square that are clearly [inside]
24+
/// (or outside) of [path].
25+
List<Offset> samplePoints(Path path, {required bool inside}) {
26+
const step = 0.09;
27+
const margin = 0.02;
28+
29+
final List<Offset> points = <Offset>[];
30+
for (var x = step; x < 1; x += step) {
31+
for (var y = step; y < 1; y += step) {
32+
final bool clearlyInOrOut = <Offset>[
33+
Offset(x, y),
34+
Offset(x - margin, y),
35+
Offset(x + margin, y),
36+
Offset(x, y - margin),
37+
Offset(x, y + margin),
38+
].every((Offset point) => path.contains(point) == inside);
39+
if (clearlyInOrOut) {
40+
points.add(Offset(x, y));
41+
}
42+
}
43+
}
44+
return points;
45+
}
46+
47+
testWidgets('Material shapes morph through every shape and wrap around', (
48+
WidgetTester tester,
49+
) async {
50+
await tester.pumpWidget(const example.MaterialShapesExampleApp());
51+
52+
expect(find.text('Material 3 Expressive Shapes Sample'), findsOne);
53+
54+
final Finder shape = find.descendant(
55+
of: find.byType(example.MaterialShapesExample),
56+
matching: find.byType(DecoratedBox),
57+
);
58+
expect(tester.getSize(shape), const Size.square(side));
59+
60+
final ThemeData theme = Theme.of(
61+
tester.element(find.byType(example.MaterialShapesExample)),
62+
);
63+
64+
// The circle is painted first, filling the paint area, and is held still
65+
// before the morphing starts.
66+
expect(
67+
shape,
68+
paints..path(
69+
color: theme.colorScheme.primary,
70+
style: PaintingStyle.fill,
71+
includes: scaled(const <Offset>[Offset(0.5, 0.5)]),
72+
excludes: scaled(const <Offset>[Offset(0.1, 0.1)]),
73+
),
74+
);
75+
expect(tester.hasRunningAnimations, isFalse);
76+
77+
// The morphing starts after holding the first shape for a second.
78+
await tester.pump(const Duration(seconds: 1));
79+
80+
// Morph through the whole list of shapes, wrapping around from the last
81+
// shape back to the first one.
82+
final shapeCount = MaterialShapes.all.length;
83+
for (var i = 0; i < shapeCount; i++) {
84+
expect(tester.hasRunningAnimations, isTrue);
85+
await tester.pump(morphDuration);
86+
87+
final RoundedPolygon target = MaterialShapes.all[(i + 1) % shapeCount];
88+
final Path targetPath = MaterialShapeBorder(
89+
shape: target,
90+
).getOuterPath(const Rect.fromLTWH(0, 0, 1, 1));
91+
expect(
92+
shape,
93+
paints..path(
94+
color: theme.colorScheme.primary,
95+
style: PaintingStyle.fill,
96+
includes: scaled(samplePoints(targetPath, inside: true)),
97+
excludes: scaled(samplePoints(targetPath, inside: false)),
98+
),
99+
reason:
100+
'Morph $i should have settled on shape ${(i + 1) % shapeCount}.',
101+
);
102+
}
103+
104+
// Disposing the example stops the animation.
105+
await tester.pumpWidget(const SizedBox());
106+
expect(tester.hasRunningAnimations, isFalse);
107+
});
108+
}

‎packages/material_ui/lib/material_ui.dart‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,8 @@ export 'src/magnifier.dart';
120120
export 'src/material.dart';
121121
export 'src/material_button.dart';
122122
export 'src/material_localizations.dart';
123+
export 'src/material_shape_border.dart' show MaterialShapeBorder;
124+
export 'src/material_shapes.dart';
123125
export 'src/material_state.dart';
124126
export 'src/material_state_mixin.dart';
125127
export 'src/menu_anchor.dart';
@@ -166,6 +168,7 @@ export 'src/segmented_button_theme.dart';
166168
export 'src/selectable_text.dart';
167169
export 'src/selection_area.dart';
168170
export 'src/shadows.dart';
171+
export 'src/shapes/shapes.dart';
169172
export 'src/slider.dart';
170173
export 'src/slider_parts.dart';
171174
export 'src/slider_theme.dart';

0 commit comments

Comments
 (0)