Reverts flutter/flutter#144001
Initiated by: Piinks
Reason for reverting: Failing goldens at the tip of tree
Original PR Author: QuncCccccc
Reviewed By: {HansMuller}
This change reverts the following previous change:
Original Description:
Reverts flutter/flutter#143973
This is a reland for #138521 with an updated g3fix(cl/605555997). Local test: cl/609608958.
## Description
This PR adds more documentation for `TextEditingController(String text)` constructor and it adds one example.
https://github.com/flutter/flutter/pull/96245 was a first improvement to the documentation.
https://github.com/flutter/flutter/issues/79495 tried to hide the cursor when an invalid selection is set but it was reverted.
https://github.com/flutter/flutter/pull/123777 mitigated the issue of having a default invalid selection: it takes care of setting a proper selection when a text field is focused and its controller selection is not initialized.
I will try changing the initial selection in another PR, but It will probably break several existing tests.
## Related Issue
Fixes https://github.com/flutter/flutter/issues/95978
## Tests
Adds 1 test for the new example.
Reland https://github.com/flutter/flutter/pull/141818 with a fix for a special case: If only `background` is specified for `TextButton.styleFrom` or `OutlinedButton.styleFrom` it applies the button's disabled state, i.e. as if the same value had been specified for disabledBackgroundColor.
The change relative to #141818 is the indicated line below:
```dart
final MaterialStateProperty<Color?>? backgroundColorProp = switch ((backgroundColor, disabledBackgroundColor)) {
(null, null) => null,
(_, null) => MaterialStatePropertyAll<Color?>(backgroundColor), // ADDED THIS LINE
(_, _) => _TextButtonDefaultColor(backgroundColor, disabledBackgroundColor),
};
```
This backwards incompatibility cropped up in an internal test, see internal Google issue b/323399158.
Reverts flutter/flutter#141818
Initiated by: XilaiZhang
This change reverts the following previous change:
Original Description:
Fixes https://github.com/flutter/flutter/issues/139456, https://github.com/flutter/flutter/issues/130335, https://github.com/flutter/flutter/issues/89563.
Two new properties have been added to ButtonStyle to make it possible to insert arbitrary state-dependent widgets in a button's background or foreground. These properties can be specified for an individual button, using the style parameter, or for all buttons using a button theme's style parameter.
The new ButtonStyle properties are `backgroundBuilder` and `foregroundBuilder` and their (function) types are:
```dart
typedef ButtonLayerBuilder = Widget Function(
BuildContext context,
Set<MaterialState> states,
Widget? child
);
```
The new builder functions are called whenever the button is built and the `states` parameter communicates the pressed/hovered/etc state fo the button.
## `backgroundBuilder`
Creates a widget that becomes the child of the button's Material and whose child is the rest of the button, including the button's `child` parameter. By default the returned widget is clipped to the Material's ButtonStyle.shape.
The `backgroundBuilder` can be used to add a gradient to the button's background. Here's an example that creates a yellow/orange gradient background:

```dart
TextButton(
onPressed: () {},
style: TextButton.styleFrom(
backgroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) {
return DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(colors: [Colors.orange, Colors.yellow]),
),
child: child,
);
},
),
child: Text('Text Button'),
)
```
Because the background widget becomes the child of the button's Material, if it's opaque (as it is in this case) then it obscures the overlay highlights which are painted on the button's Material. To ensure that the highlights show through one can decorate the background with an `Ink` widget. This version also overrides the overlay color to be (shades of) red, because that makes the highlights look a little nicer with the yellow/orange background.

```dart
TextButton(
onPressed: () {},
style: TextButton.styleFrom(
overlayColor: Colors.red,
backgroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) {
return Ink(
decoration: BoxDecoration(
gradient: LinearGradient(colors: [Colors.orange, Colors.yellow]),
),
child: child,
);
},
),
child: Text('Text Button'),
)
```
Now the button's overlay highlights are painted on the Ink widget. An Ink widget isn't needed if the background is sufficiently translucent. This version of the example creates a translucent backround widget.

```dart
TextButton(
onPressed: () {},
style: TextButton.styleFrom(
overlayColor: Colors.red,
backgroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) {
return DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(colors: [
Colors.orange.withOpacity(0.5),
Colors.yellow.withOpacity(0.5),
]),
),
child: child,
);
},
),
child: Text('Text Button'),
)
```
One can also decorate the background with an image. In this example, the button's background is an burlap texture image. The foreground color has been changed to black to make the button's text a little clearer relative to the mottled brown backround.

```dart
TextButton(
onPressed: () {},
style: TextButton.styleFrom(
foregroundColor: Colors.black,
backgroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) {
return Ink(
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(burlapUrl),
fit: BoxFit.cover,
),
),
child: child,
);
},
),
child: Text('Text Button'),
)
```
The background widget can depend on the `states` parameter. In this example the blue/orange gradient flips horizontally when the button is hovered/pressed.

```dart
TextButton(
onPressed: () {},
style: TextButton.styleFrom(
backgroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) {
final Color color1 = Colors.blue.withOpacity(0.5);
final Color color2 = Colors.orange.withOpacity(0.5);
return DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: switch (states.contains(MaterialState.hovered)) {
true => <Color>[color1, color2],
false => <Color>[color2, color1],
},
),
),
child: child,
);
},
),
child: Text('Text Button'),
)
```
The preceeding examples have not included a BoxDecoration border because ButtonStyle already supports `ButtonStyle.shape` and `ButtonStyle.side` parameters that can be uesd to define state-dependent borders. Borders defined with the ButtonStyle side parameter match the button's shape. To add a border that changes color when the button is hovered or pressed, one must specify the side property using `copyWith`, since there's no `styleFrom` shorthand for this case.

```dart
TextButton(
onPressed: () {},
style: TextButton.styleFrom(
foregroundColor: Colors.indigo,
backgroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) {
final Color color1 = Colors.blue.withOpacity(0.5);
final Color color2 = Colors.orange.withOpacity(0.5);
return DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: switch (states.contains(MaterialState.hovered)) {
true => <Color>[color1, color2],
false => <Color>[color2, color1],
},
),
),
child: child,
);
},
).copyWith(
side: MaterialStateProperty.resolveWith<BorderSide?>((Set<MaterialState> states) {
if (states.contains(MaterialState.hovered)) {
return BorderSide(width: 3, color: Colors.yellow);
}
return null; // defer to the default
}),
),
child: Text('Text Button'),
)
```
Although all of the examples have created a ButtonStyle locally and only applied it to one button, they could have configured the `ThemeData.textButtonTheme` instead and applied the style to all TextButtons. And, of course, all of this works for all of the ButtonStyleButton classes, not just TextButton.
## `foregroundBuilder`
Creates a Widget that contains the button's child parameter. The returned widget is clipped by the button's [ButtonStyle.shape] inset by the button's [ButtonStyle.padding] and aligned by the button's [ButtonStyle.alignment].
The `foregroundBuilder` can be used to wrap the button's child, e.g. with a border or a `ShaderMask` or as a state-dependent substitute for the child.
This example adds a border that's just applied to the child. The border only appears when the button is hovered/pressed.

```dart
ElevatedButton(
onPressed: () {},
style: ElevatedButton.styleFrom(
foregroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) {
final ColorScheme colorScheme = Theme.of(context).colorScheme;
return DecoratedBox(
decoration: BoxDecoration(
border: states.contains(MaterialState.hovered)
? Border(bottom: BorderSide(color: colorScheme.primary))
: Border(), // essentially "no border"
),
child: child,
);
},
),
child: Text('Text Button'),
)
```
The foregroundBuilder can be used with `ShaderMask` to change the way the button's child is rendered. In this example the ShaderMask's gradient causes the button's child to fade out on top.

```dart
ElevatedButton(
onPressed: () { },
style: ElevatedButton.styleFrom(
foregroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) {
final ColorScheme colorScheme = Theme.of(context).colorScheme;
return ShaderMask(
shaderCallback: (Rect bounds) {
return LinearGradient(
begin: Alignment.bottomCenter,
end: Alignment.topCenter,
colors: <Color>[
colorScheme.primary,
colorScheme.primaryContainer,
],
).createShader(bounds);
},
blendMode: BlendMode.srcATop,
child: child,
);
},
),
child: const Text('Elevated Button'),
)
```
A commonly requested configuration for butttons has the developer provide images, one for pressed/hovered/normal state. You can use the foregroundBuilder to create a button that fades between a normal image and another image when the button is pressed. In this case the foregroundBuilder doesn't use the child it's passed, even though we've provided the required TextButton child parameter.

```dart
TextButton(
onPressed: () {},
style: TextButton.styleFrom(
foregroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) {
final String url = states.contains(MaterialState.pressed) ? smiley2Url : smiley1Url;
return AnimatedContainer(
width: 100,
height: 100,
duration: Duration(milliseconds: 300),
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(url),
fit: BoxFit.contain,
),
),
);
},
),
child: Text('No Child'),
)
```
In this example the button's default overlay appears when the button is hovered and pressed. Another image can be used to indicate the hovered state and the default overlay can be defeated by specifying `Colors.transparent` for the `overlayColor`:

```dart
TextButton(
onPressed: () {},
style: TextButton.styleFrom(
overlayColor: Colors.transparent,
foregroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) {
String url = states.contains(MaterialState.hovered) ? smiley3Url : smiley1Url;
if (states.contains(MaterialState.pressed)) {
url = smiley2Url;
}
return AnimatedContainer(
width: 100,
height: 100,
duration: Duration(milliseconds: 300),
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(url),
fit: BoxFit.contain,
),
),
);
},
),
child: Text('No Child'),
)
```
Fixes https://github.com/flutter/flutter/issues/139456, https://github.com/flutter/flutter/issues/130335, https://github.com/flutter/flutter/issues/89563.
Two new properties have been added to ButtonStyle to make it possible to insert arbitrary state-dependent widgets in a button's background or foreground. These properties can be specified for an individual button, using the style parameter, or for all buttons using a button theme's style parameter.
The new ButtonStyle properties are `backgroundBuilder` and `foregroundBuilder` and their (function) types are:
```dart
typedef ButtonLayerBuilder = Widget Function(
BuildContext context,
Set<MaterialState> states,
Widget? child
);
```
The new builder functions are called whenever the button is built and the `states` parameter communicates the pressed/hovered/etc state fo the button.
## `backgroundBuilder`
Creates a widget that becomes the child of the button's Material and whose child is the rest of the button, including the button's `child` parameter. By default the returned widget is clipped to the Material's ButtonStyle.shape.
The `backgroundBuilder` can be used to add a gradient to the button's background. Here's an example that creates a yellow/orange gradient background:

```dart
TextButton(
onPressed: () {},
style: TextButton.styleFrom(
backgroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) {
return DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(colors: [Colors.orange, Colors.yellow]),
),
child: child,
);
},
),
child: Text('Text Button'),
)
```
Because the background widget becomes the child of the button's Material, if it's opaque (as it is in this case) then it obscures the overlay highlights which are painted on the button's Material. To ensure that the highlights show through one can decorate the background with an `Ink` widget. This version also overrides the overlay color to be (shades of) red, because that makes the highlights look a little nicer with the yellow/orange background.

```dart
TextButton(
onPressed: () {},
style: TextButton.styleFrom(
overlayColor: Colors.red,
backgroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) {
return Ink(
decoration: BoxDecoration(
gradient: LinearGradient(colors: [Colors.orange, Colors.yellow]),
),
child: child,
);
},
),
child: Text('Text Button'),
)
```
Now the button's overlay highlights are painted on the Ink widget. An Ink widget isn't needed if the background is sufficiently translucent. This version of the example creates a translucent backround widget.

```dart
TextButton(
onPressed: () {},
style: TextButton.styleFrom(
overlayColor: Colors.red,
backgroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) {
return DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(colors: [
Colors.orange.withOpacity(0.5),
Colors.yellow.withOpacity(0.5),
]),
),
child: child,
);
},
),
child: Text('Text Button'),
)
```
One can also decorate the background with an image. In this example, the button's background is an burlap texture image. The foreground color has been changed to black to make the button's text a little clearer relative to the mottled brown backround.

```dart
TextButton(
onPressed: () {},
style: TextButton.styleFrom(
foregroundColor: Colors.black,
backgroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) {
return Ink(
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(burlapUrl),
fit: BoxFit.cover,
),
),
child: child,
);
},
),
child: Text('Text Button'),
)
```
The background widget can depend on the `states` parameter. In this example the blue/orange gradient flips horizontally when the button is hovered/pressed.

```dart
TextButton(
onPressed: () {},
style: TextButton.styleFrom(
backgroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) {
final Color color1 = Colors.blue.withOpacity(0.5);
final Color color2 = Colors.orange.withOpacity(0.5);
return DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: switch (states.contains(MaterialState.hovered)) {
true => <Color>[color1, color2],
false => <Color>[color2, color1],
},
),
),
child: child,
);
},
),
child: Text('Text Button'),
)
```
The preceeding examples have not included a BoxDecoration border because ButtonStyle already supports `ButtonStyle.shape` and `ButtonStyle.side` parameters that can be uesd to define state-dependent borders. Borders defined with the ButtonStyle side parameter match the button's shape. To add a border that changes color when the button is hovered or pressed, one must specify the side property using `copyWith`, since there's no `styleFrom` shorthand for this case.

```dart
TextButton(
onPressed: () {},
style: TextButton.styleFrom(
foregroundColor: Colors.indigo,
backgroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) {
final Color color1 = Colors.blue.withOpacity(0.5);
final Color color2 = Colors.orange.withOpacity(0.5);
return DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: switch (states.contains(MaterialState.hovered)) {
true => <Color>[color1, color2],
false => <Color>[color2, color1],
},
),
),
child: child,
);
},
).copyWith(
side: MaterialStateProperty.resolveWith<BorderSide?>((Set<MaterialState> states) {
if (states.contains(MaterialState.hovered)) {
return BorderSide(width: 3, color: Colors.yellow);
}
return null; // defer to the default
}),
),
child: Text('Text Button'),
)
```
Although all of the examples have created a ButtonStyle locally and only applied it to one button, they could have configured the `ThemeData.textButtonTheme` instead and applied the style to all TextButtons. And, of course, all of this works for all of the ButtonStyleButton classes, not just TextButton.
## `foregroundBuilder`
Creates a Widget that contains the button's child parameter. The returned widget is clipped by the button's [ButtonStyle.shape] inset by the button's [ButtonStyle.padding] and aligned by the button's [ButtonStyle.alignment].
The `foregroundBuilder` can be used to wrap the button's child, e.g. with a border or a `ShaderMask` or as a state-dependent substitute for the child.
This example adds a border that's just applied to the child. The border only appears when the button is hovered/pressed.

```dart
ElevatedButton(
onPressed: () {},
style: ElevatedButton.styleFrom(
foregroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) {
final ColorScheme colorScheme = Theme.of(context).colorScheme;
return DecoratedBox(
decoration: BoxDecoration(
border: states.contains(MaterialState.hovered)
? Border(bottom: BorderSide(color: colorScheme.primary))
: Border(), // essentially "no border"
),
child: child,
);
},
),
child: Text('Text Button'),
)
```
The foregroundBuilder can be used with `ShaderMask` to change the way the button's child is rendered. In this example the ShaderMask's gradient causes the button's child to fade out on top.

```dart
ElevatedButton(
onPressed: () { },
style: ElevatedButton.styleFrom(
foregroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) {
final ColorScheme colorScheme = Theme.of(context).colorScheme;
return ShaderMask(
shaderCallback: (Rect bounds) {
return LinearGradient(
begin: Alignment.bottomCenter,
end: Alignment.topCenter,
colors: <Color>[
colorScheme.primary,
colorScheme.primaryContainer,
],
).createShader(bounds);
},
blendMode: BlendMode.srcATop,
child: child,
);
},
),
child: const Text('Elevated Button'),
)
```
A commonly requested configuration for butttons has the developer provide images, one for pressed/hovered/normal state. You can use the foregroundBuilder to create a button that fades between a normal image and another image when the button is pressed. In this case the foregroundBuilder doesn't use the child it's passed, even though we've provided the required TextButton child parameter.

```dart
TextButton(
onPressed: () {},
style: TextButton.styleFrom(
foregroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) {
final String url = states.contains(MaterialState.pressed) ? smiley2Url : smiley1Url;
return AnimatedContainer(
width: 100,
height: 100,
duration: Duration(milliseconds: 300),
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(url),
fit: BoxFit.contain,
),
),
);
},
),
child: Text('No Child'),
)
```
In this example the button's default overlay appears when the button is hovered and pressed. Another image can be used to indicate the hovered state and the default overlay can be defeated by specifying `Colors.transparent` for the `overlayColor`:

```dart
TextButton(
onPressed: () {},
style: TextButton.styleFrom(
overlayColor: Colors.transparent,
foregroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) {
String url = states.contains(MaterialState.hovered) ? smiley3Url : smiley1Url;
if (states.contains(MaterialState.pressed)) {
url = smiley2Url;
}
return AnimatedContainer(
width: 100,
height: 100,
duration: Duration(milliseconds: 300),
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(url),
fit: BoxFit.contain,
),
),
);
},
),
child: Text('No Child'),
)
```
Fixes #140770 and #103124
Adds the possibility of passing a height and width to icons. And also a margin for the distance of the lines between the icons.
fixes [`RouteObserver` example throws an error](https://github.com/flutter/flutter/issues/141078)
### Description
This updates the `RouteObserver` example from snippet to Dartpad example and fixes the error when running the code snippet
fixes https://github.com/flutter/flutter/issues/138289
---
SegmentedButtom.styleFrom has been added to the segment button, so there is no longer any need to the button style from the beginning. It works like ElevatedButton.styleFrom only I added selectedForegroundColor, selectedBackgroundColor. In this way, the user will be able to change the color first without checking the MaterialState states. I added tests of the same controls.
#129215 I opened this problem myself, but I was rejected because I handled too many items in a PR. For now, I wrote a structure that only handles MaterialStates instead of users.
old (still avaliable)
<img width="626" alt="image" src="https://github.com/flutter/flutter/assets/65075121/9446b13b-c355-4d20-bda2-c47a23d42d4f">
new (just an option for developer)
<img width="483" alt="image" src="https://github.com/flutter/flutter/assets/65075121/0a645257-4c83-4029-9484-bd746c02265f">
### Code sample
<details>
<summary>expand to view the code sample</summary>
```dart
import 'package:flutter/material.dart';
/// Flutter code sample for [SegmentedButton].
void main() {
runApp(const SegmentedButtonApp());
}
enum Calendar { day, week, month, year }
class SegmentedButtonApp extends StatefulWidget {
const SegmentedButtonApp({super.key});
@override
State<SegmentedButtonApp> createState() => _SegmentedButtonAppState();
}
class _SegmentedButtonAppState extends State<SegmentedButtonApp> {
Calendar calendarView = Calendar.day;
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
home: Scaffold(
body: Center(
child: SegmentedButton<Calendar>(
style: SegmentedButton.styleFrom(
foregroundColor: Colors.amber,
visualDensity: VisualDensity.comfortable,
),
// style: const ButtonStyle(
// foregroundColor: MaterialStatePropertyAll<Color>(Colors.deepPurple),
// visualDensity: VisualDensity.comfortable,
// ),
segments: const <ButtonSegment<Calendar>>[
ButtonSegment<Calendar>(
value: Calendar.day,
label: Text('Day'),
icon: Icon(Icons.calendar_view_day)),
ButtonSegment<Calendar>(
value: Calendar.week,
label: Text('Week'),
icon: Icon(Icons.calendar_view_week)),
ButtonSegment<Calendar>(
value: Calendar.month,
label: Text('Month'),
icon: Icon(Icons.calendar_view_month)),
ButtonSegment<Calendar>(
value: Calendar.year,
label: Text('Year'),
icon: Icon(Icons.calendar_today)),
],
selected: <Calendar>{calendarView},
onSelectionChanged: (Set<Calendar> newSelection) {
setState(() {
calendarView = newSelection.first;
});
},
),
),
),
);
}
}
```
</details>
Thanks so much for approving the previous PR (#139048) a couple weeks ago!
This one is the same, except it's covering files in `examples/` and `packages/flutter/lib/src/animation/`.
(solving issue #136139)
This change fixes issues with screen order comparison logic when rects are encompassed within each other. This was causing issues when trying to select text that includes inline `WidgetSpan`s inside of a `SelectionArea`.
* Adds `boundingBoxes` to `Selectable` for a more precise hit testing region.
Fixes#132821
Fixes updating selection edge by word boundary when widget spans are involved.
Fixes crash when sending select word selection event to an unselectable element.
Reverts flutter/flutter#137945
Initiated by: HansMuller
This change reverts the following previous change:
Original Description:
This PR introduces `AnimationStyle`, it is used to override default animation curves and durations in several widgets.
fixes [Add the ability to customize MaterialApp theme animation duration](https://github.com/flutter/flutter/issues/78372)
fixes [Allow customization of showMenu transition animation curves and duration](https://github.com/flutter/flutter/issues/135638)
Here is an example where popup menu curve and transition duration is overriden:
```dart
popUpAnimationStyle: AnimationStyle(
curve: Easing.emphasizedAccelerate,
duration: Durations.medium4,
),
```
Set `AnimationStyle.noAnimation` to disable animation.
```dart
return MaterialApp(
themeAnimationStyle: AnimationStyle.noAnimation,
```
This PR introduces `AnimationStyle`, it is used to override default animation curves and durations in several widgets.
fixes [Add the ability to customize MaterialApp theme animation duration](https://github.com/flutter/flutter/issues/78372)
fixes [Allow customization of showMenu transition animation curves and duration](https://github.com/flutter/flutter/issues/135638)
Here is an example where popup menu curve and transition duration is overriden:
```dart
popUpAnimationStyle: AnimationStyle(
curve: Easing.emphasizedAccelerate,
duration: Durations.medium4,
),
```
Set `AnimationStyle.noAnimation` to disable animation.
```dart
return MaterialApp(
themeAnimationStyle: AnimationStyle.noAnimation,
```
### Description
This PR intends to update `DraggableScrollableSheet` docs for Web and Desktop platforms. On these platforms, the vertical dragging gesture does not provide natural behavior similar to other desktop applications.
By adding a note before the sample code so users are aware that the sample code will not work as expected on Desktop and Web. Also, refer to the instructions if they still want to implement it on these platforms.
### Related issue
Fixes https://github.com/flutter/flutter/issues/111372
This example shows how to use `AnimationController` and
`SlideTransition` to create an animated digit like you might find on a
digital clock. New digit values slide into place from below, as the old
value slides upwards and out of view. Taps that occur while the
controller is already animating cause the controller's
`AnimationController.duration` to be reduced so that the visuals don't
fall behind.
You can try the example here:
https://dartpad.dev/?id=9553c20fe0fdb0c5447c1293e02400eb
Currently, `Switch.factory` delegates to `CupertinoSwitch` when platform
is iOS or macOS. This PR is to:
* have the factory configure the Material `Switch` for the expected look
and feel.
* introduce `Adaptation` class to customize themes for the adaptive
components.
Updated the NavigationBar API doc that describes
examples/api/lib/material/navigation_bar/navigation_bar.2.dart and made
some cosmetic changes to the example to improve its appearance in
Material 3. Also did a little gratuitous reformatting.
Fixes#136125
Fixes#119401
This PR is to:
* add `Card.filled` and `Card.outlined` factory methods so that we can use tokens for these two types of cards to generate default theme instead of providing hard-corded values in example.
* update card.2.dart example.
* add test file for card.2.dart example.
* fix some mismatch caused by editing the auto-generated defaults by hand in navigation_bar.dart and navigation_drawer.dart.
*Replace this paragraph with a description of what this PR is changing or adding, and why. Consider including before/after screenshots.*
fix some typos
*List which issues are fixed by this PR. You must list at least one issue.*
*If you had to change anything in the [flutter/tests] repo, include a link to the migration guide as per the [breaking change policy].*
## Description
This converts the `MenuAnchor` class to use `OverlayPortal` instead of directly using the overlay.
## Related Issues
- Fixes https://github.com/flutter/flutter/issues/124830
## Tests
- No tests yet (hence it is a draft)
The documentation for using `findChildIndexCallback` recommends using `indexOf`, but that causes [this line](05259ca938/packages/flutter/lib/src/rendering/sliver_multi_box_adaptor.dart (L259)) to throw in debug mode, and when using `SliverList`, it breaks the render.
This PR changes the usage to check if the index is not negative before using it, and changes to return `null` instead if the child wasn't able to be found.
There's the related issue #107123, but this doesn't actually fix it.
-----
This PR has been updated to add the snippets that were used in the `findChildIndexCallback` comment as examples with proper tests, as well as updating the comment to reference the new examples.
## Description
This converts some usages of `RawKeyEvent` to `KeyEvent` to prepare the repo for deprecation of `RawKeyEvent`, and swaps out the `raw_keyboard.dart` manual test for `hardware_keyboard.dart`.
## Related Issues
- https://github.com/flutter/flutter/issues/136419
## Tests
- Just refactoring code, no semantic changes.
## Description
In order for `MenuAnchor` menus to be able to not pass on the taps that close their menus, `TapRegion` needed a way to consume them. This change adds a flag to the `TapRegion`, `consumeOutsideTap` that will consume taps that occur outside of the region if the flag is set (it is false by default). The same flag is added to `MenuAnchor` to allow selecting the behavior for menus.
`TapRegion` consumes the tap event by registering with the gesture arena and immediately resolving the tap as accepted if any regions in a group have `consumeOutsideTap` set to true.
This PR also deprecates `MenuAnchor.anchorTapClosesMenu`, since it is a much more limited version of the same feature that only applied to the anchor itself, and even then only applied to closing the menu, not passing along the tap. The same functionality can now be implemented by handling a tap on the anchor widget and checking to see if the menu is open before closing it.
## Related Issues
- https://github.com/flutter/flutter/issues/135327
## Tests
- Added tests for `TapRegion` to make sure taps are consumed properly.
Reverts flutter/flutter#125927
context: b/300804374
Looks like a g3 fix might involve changing the names of widget on the customer app, and I am not sure if that would be the right approach forward. Putting up a revert to be safe for now.
New example for `InputChip` that demonstrate how to create/delete them based on user text inputs.
The sample application shows a custom text area where user can enter text. After the user has typed and hits _Enter_ the text will be replaced with an `InputChip` that contains that text. Is it possible to continue typing and add more chips in this way. All of them will be placed in a scrollable horizontal row. Also is it possible to have suggestion displayed below the text input field in case the typed text match some of the available suggestions.
Issue I'm trying to solve:
- https://github.com/flutter/flutter/issues/128247
**Code structure:**
The example app is composed of 2 main components that find places inside `MainScreen`:
- `ChipsInput`
- `ListView`
`ChipsInput` emulates a `TextField` where you can enter text. This text field accepts also a list of values of generic type T (`Topping` in my example), that gets rendered as `InputChip` inside the text field, before the text inserted by the user. This widgets is basically an `InputDecorator` widget that implements `TextInputClient` to get `TextEditingValue` events from the user keyboard. At the end of the input field there is another component, the `TextCursor`, that is displayed just when the user give the focus to the field and emulates the carrets that `TextField` has.
There are also some available callbacks that the user can use to capture events in the `ChipsInput` field like: `onChanged`, `onChipTapped`, `onSubmitted` and `onTextChanged`. This last callback is used to build a list of suggestion that will be placed just below the `ChipsInput` field inside the `ListView`.
- slightly improved assert message when row cell counts don't match column count.
- more breadcrumbs in API documentation. more documentation in general.
- added more documentation for the direction of the "ascending" arrow.
- two samples for PaginatedDataTable.
- make PaginatedDataTable support hot reloading across changes to the number of columns.
- introduce matrix3MoreOrLessEquals. An earlier version of this PR used it in tests, but eventually it was not needed. The function seems useful to keep though.
This PR aims to support Android's predictive back gesture when popping the entire Flutter app. Predictive route transitions between routes inside of a Flutter app will come later.
<img width="200" src="https://user-images.githubusercontent.com/389558/217918109-945febaa-9086-41cc-a476-1a189c7831d8.gif" />
### Trying it out
If you want to try this feature yourself, here are the necessary steps:
1. Run Android 33 or above.
1. Enable the feature flag for predictive back on the device under "Developer
options".
1. Create a Flutter project, or clone [my example project](https://github.com/justinmc/flutter_predictive_back_examples).
1. Set `android:enableOnBackInvokedCallback="true"` in
android/app/src/main/AndroidManifest.xml (already done in the example project).
1. Check out this branch.
1. Run the app. Perform a back gesture (swipe from the left side of the
screen).
You should see the predictive back animation like in the animation above and be able to commit or cancel it.
### go_router support
go_router works with predictive back out of the box because it uses a Navigator internally that dispatches NavigationNotifications!
~~go_router can be supported by adding a listener to the router and updating SystemNavigator.setFrameworkHandlesBack.~~
Similar to with nested Navigators, nested go_routers is supported by using a PopScope widget.
<details>
<summary>Full example of nested go_routers</summary>
```dart
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:go_router/go_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
void main() => runApp(_MyApp());
class _MyApp extends StatelessWidget {
final GoRouter router = GoRouter(
routes: <RouteBase>[
GoRoute(
path: '/',
builder: (BuildContext context, GoRouterState state) => _HomePage(),
),
GoRoute(
path: '/nested_navigators',
builder: (BuildContext context, GoRouterState state) => _NestedGoRoutersPage(),
),
],
);
@override
Widget build(BuildContext context) {
return MaterialApp.router(
routerConfig: router,
);
}
}
class _HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Nested Navigators Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text('Home Page'),
const Text('A system back gesture here will exit the app.'),
const SizedBox(height: 20.0),
ListTile(
title: const Text('Nested go_router route'),
subtitle: const Text('This route has another go_router in addition to the one used with MaterialApp above.'),
onTap: () {
context.push('/nested_navigators');
},
),
],
),
),
);
}
}
class _NestedGoRoutersPage extends StatefulWidget {
@override
State<_NestedGoRoutersPage> createState() => _NestedGoRoutersPageState();
}
class _NestedGoRoutersPageState extends State<_NestedGoRoutersPage> {
late final GoRouter _router;
final GlobalKey<NavigatorState> _nestedNavigatorKey = GlobalKey<NavigatorState>();
// If the nested navigator has routes that can be popped, then we want to
// block the root navigator from handling the pop so that the nested navigator
// can handle it instead.
bool get _popEnabled {
// canPop will throw an error if called before build. Is this the best way
// to avoid that?
return _nestedNavigatorKey.currentState == null ? true : !_router.canPop();
}
void _onRouterChanged() {
// Here the _router reports the location correctly, but canPop is still out
// of date. Hence the post frame callback.
SchedulerBinding.instance.addPostFrameCallback((Duration duration) {
setState(() {});
});
}
@override
void initState() {
super.initState();
final BuildContext rootContext = context;
_router = GoRouter(
navigatorKey: _nestedNavigatorKey,
routes: [
GoRoute(
path: '/',
builder: (BuildContext context, GoRouterState state) => _LinksPage(
title: 'Nested once - home route',
backgroundColor: Colors.indigo,
onBack: () {
rootContext.pop();
},
buttons: <Widget>[
TextButton(
onPressed: () {
context.push('/two');
},
child: const Text('Go to another route in this nested Navigator'),
),
],
),
),
GoRoute(
path: '/two',
builder: (BuildContext context, GoRouterState state) => _LinksPage(
backgroundColor: Colors.indigo.withBlue(255),
title: 'Nested once - page two',
),
),
],
);
_router.addListener(_onRouterChanged);
}
@override
void dispose() {
_router.removeListener(_onRouterChanged);
super.dispose();
}
@override
Widget build(BuildContext context) {
return PopScope(
popEnabled: _popEnabled,
onPopped: (bool success) {
if (success) {
return;
}
_router.pop();
},
child: Router<Object>.withConfig(
restorationScopeId: 'router-2',
config: _router,
),
);
}
}
class _LinksPage extends StatelessWidget {
const _LinksPage ({
required this.backgroundColor,
this.buttons = const <Widget>[],
this.onBack,
required this.title,
});
final Color backgroundColor;
final List<Widget> buttons;
final VoidCallback? onBack;
final String title;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: backgroundColor,
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(title),
//const Text('A system back here will go back to Nested Navigators Page One'),
...buttons,
TextButton(
onPressed: onBack ?? () {
context.pop();
},
child: const Text('Go back'),
),
],
),
),
);
}
}
```
</details>
### Resources
Fixes https://github.com/flutter/flutter/issues/109513
Depends on engine PR https://github.com/flutter/engine/pull/39208✔️
Design doc: https://docs.google.com/document/d/1BGCWy1_LRrXEB6qeqTAKlk-U2CZlKJ5xI97g45U7azk/edit#
Migration guide: https://github.com/flutter/website/pull/8952
Deprecate `textScaleFactor` in favor of `textScaler`, in preparation for Android 14 [Non-linear font scaling to 200%](https://developer.android.com/about/versions/14/features#non-linear-font-scaling). The `TextScaler` class can be moved to `dart:ui` in the future, if we decide to use the Android platform API or AndroidX to get the scaling curve instead of hard coding the curve in the framework.
I haven't put the Flutter version in the deprecation message so the analyzer checks are failing. Will do so after I finish the migration guide.
**Why `TextScaler.textScaleFactor`**
The author of a `TextScaler` subclass should provide a fallback `textScaleFactor`. By making `TextScaler` also contain the `textScaleFactor` information it also makes it easier to migrate: if a widget overrides `MediaQueryData.textScaler` in the tree, for unmigrated widgets in the subtree it would also have to override `MediaQueryData.textScaleFactor`, and that makes it difficult to remove `MediaQueryData.textScaleFactor` in the future.
## A full list of affected APIs in this PR
Deprecated: The method/getter/setter/argument is annotated with a `@Deprecated()` annotation in this PR, and the caller should replace it with `textScaler` instead. Unless otherwise specified there will be a Flutter fix available to help with migration but it's still recommended to migrate case-by-case.
**Replaced**: The method this `textScaleFactor` argument belongs to is rarely called directly by user code and is not overridden by any of the registered custom tests, so the argument is directly replaced by `TextScaler`.
**To Be Deprecated**: The method/getter/setter/argument can't be deprecated in this PR because a registered customer test depends on it and a Flutter fix isn't available (or the test was run without applying flutter fixes first). This method/getter/setter/argument will be deprecated in a followup PR once the registered test is migrated.
### `Painting` Library
| Affected API | State of `textScaleFactor` | Comment |
| --- | --- | --- |
| `InlineSpan.build({ double textScaleFactor = 1.0 })` argument | **Replaced** | |
| `TextStyle.getParagraphStyle({ double TextScaleFactor = 1.0 })` argument | **Replaced** | |
| `TextStyle.getTextStyle({ double TextScaleFactor = 1.0 })` argument| Deprecated | Can't replace: c47fd38dca/super_editor/lib/src/infrastructure/super_textfield/desktop/desktop_textfield.dart (L1903-L1905)|
| `TextPainter({ double TextScaleFactor = 1.0 })` constructor argument | Deprecated | |
| `TextPainter.textScaleFactor` getter and setter | Deprecated | No Flutter Fix, not expressible yet |
| `TextPainter.computeWidth({ double TextScaleFactor = 1.0 })` argument | Deprecated | |
| `TextPainter.computeMaxIntrinsicWidth({ double TextScaleFactor = 1.0 })` argument | Deprecated | |
### `Rendering` Library
| Affected API | State of `textScaleFactor` | Comment |
| --- | --- | --- |
| `RenderEditable({ double TextScaleFactor = 1.0 })` constructor argument | Deprecated | |
| `RenderEditable.textScaleFactor` getter and setter | Deprecated | No Flutter Fix, not expressible yet |
| `RenderParagraph({ double TextScaleFactor = 1.0 })` constructor argument | Deprecated | |
| `RenderParagraph.textScaleFactor` getter and setter | Deprecated | No Flutter Fix, not expressible yet |
### `Widgets` Library
| Affected API | State of `textScaleFactor` | Comment |
| --- | --- | --- |
| `MediaQueryData({ double TextScaleFactor = 1.0 })` constructor argument | **To Be Deprecated** | cd7b93532e/packages/flutter_markdown/test/text_scale_factor_test.dart (LL39C21-L39C35) |
| `MediaQueryData.textScaleFactor` getter | Deprecated | |
| `MediaQueryData.copyWith({ double? TextScaleFactor })` argument | Deprecated | |
| `MediaQuery.maybeTextScaleFactorOf(BuildContext context)` static method | Deprecated | No Flutter Fix, not expressible yet |
| `MediaQuery.textScaleFactorOf(BuildContext context)` static method | **To Be Deprecated** | cd7b93532e/packages/flutter_markdown/lib/src/_functions_io.dart (L68-L70), No Flutter Fix, not expressible yet |
| `RichText({ double TextScaleFactor = 1.0 })` constructor argument | **To Be Deprecated** | cd7b93532e/packages/flutter_markdown/lib/src/builder.dart (L829-L843) |
| `RichText.textScaleFactor` getter | **To Be Deprecated** | A constructor argument can't be deprecated right away|
| `Text({ double? TextScaleFactor = 1.0 })` constructor argument | **To Be Deprecated** | 914d120da1/packages/rfw/lib/src/flutter/core_widgets.dart (L647) , No Flutter Fix because of https://github.com/dart-lang/sdk/issues/52664 |
| `Text.rich({ double? TextScaleFactor = 1.0 })` constructor argument | **To Be Deprecated** | The default constructor has an argument that can't be deprecated right away. No Flutter Fix because of https://github.com/dart-lang/sdk/issues/52664 |
| `Text.textScaleFactor` getter | **To Be Deprecated** | A constructor argument can't be deprecated right away |
| `EditableText({ double? TextScaleFactor = 1.0 })` constructor argument | Deprecated | No Flutter Fix because of https://github.com/dart-lang/sdk/issues/52664 |
| `EditableText.textScaleFactor` getter | Deprecated | |
### `Material` Library
| Affected API | State of `textScaleFactor` | Comment |
| --- | --- | --- |
| `SelectableText({ double? TextScaleFactor = 1.0 })` constructor argument | **To Be Deprecated** | cd7b93532e/packages/flutter_markdown/lib/src/builder.dart (L829-L843), No Flutter Fix because of https://github.com/dart-lang/sdk/issues/52664 |
| `SelectableText.rich({ double? TextScaleFactor = 1.0 })` constructor argument | **To Be Deprecated** | The default constructor has an argument that can't be deprecated right away. No Flutter Fix because of https://github.com/dart-lang/sdk/issues/52664 |
| `SelectableText.textScaleFactor` getter | **To Be Deprecated** | A constructor argument can't be deprecated right away |
A lot of material widgets (`Slider`, `RangeSlider`, `TimePicker`, and different types of buttons) also change their layout based on `textScaleFactor`. These need to be handled in a case-by-case fashion and will be migrated in follow-up PRs.
This PR changes the example app into a custom scrollview with three slivers. The middle sliver has a nested scrollview of height 300 and only this nested sliver can trigger the refresh indicator.
Fixes https://github.com/flutter/flutter/issues/116237.
Updated tests in dev, examples/api, and tests/widgets to ensure that
they continue to pass when the default for `ThemeData.useMaterial3` is
changed to true.
This is the final set of changes required for
https://github.com/flutter/flutter/issues/127064.
This change updates `SelectableRegion`s right-click gesture to match native platform behavior.
Before: Right-click gesture selects word at position and opens context menu (All Platforms)
After:
- Linux, toggles context menu on/off, and collapses selection when click was not on an active selection (uncollapsed).
- Windows, Android, Fuchsia, shows context menu at right-clicked position (unless the click is at an active selection).
- macOS, toggles the context menu if right click was at the same position as the previous / or selects word at position and opens context menu.
- iOS, selects word at position and opens context menu.
This change also prevents the `copy` menu button from being shown when there is a collapsed selection (nothing to copy).
Fixes#117561
This is a second attempt to merge #107269. Currently I've fixed two of the issues:
1. Fixed horizontal scrollview by using a switch statement to consider vertical/horizontal case.
2. Fixed issue of `paintExtent` not being the right extent for painting. Rather using a `scrollExtent` for the main axis length of the decoration box and painting it offsetted by the `scrollOffset`.
3. If the sliver child has inifinite scrollExtent, then we only draw the decoration down to the bottom of the `cacheExtent`. The developer is expected to ensure that the border does not creep up above the cache area.
This PR includes a test that checks that the correct rectangle is drawn at a certain scrollOffset for both the horizontal and vertical case which should be sufficient for checking that `SliverDecoration` works properly now.
Fixes https://github.com/flutter/flutter/issues/107498.
## Description
Changes the context menu example for `MenuAnchor` so that it uses right-click, or (on macOS and iOS only) ctrl-left-click, for the context menu. Also disables the browser context menu on web platforms.
## Tests
- Updated test to reflect new triggers.
Updated the ToggleButtons example and test to M3.
Updated the nested tabs test to avoid warnings like:
```
Warning: A call to tap() with finder "exactly one widget with type "Tab" which is an ancestor of text "Explore": Tab(text: "Explore", icon: Icon)" derived an Offset (Offset(666.7, 92.0)) that would not hit test on the specified widget.
```