From b2e22d3558e8334d4427ed9b78d21a347375fad2 Mon Sep 17 00:00:00 2001 From: LongCatIsLooong <31859944+LongCatIsLooong@users.noreply.github.com> Date: Mon, 17 Jul 2023 10:56:07 -0700 Subject: [PATCH] Replaces `textScaleFactor` with `TextScaler` (#128522) 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: https://github.com/superlistapp/super_editor/blob/c47fd38dca4b7f43611690913b551a1773c563d7/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** | https://github.com/flutter/packages/blob/cd7b93532e5cb605a42735e20f1de70fc00adae7/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** | https://github.com/flutter/packages/blob/cd7b93532e5cb605a42735e20f1de70fc00adae7/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** | https://github.com/flutter/packages/blob/cd7b93532e5cb605a42735e20f1de70fc00adae7/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** | https://github.com/flutter/packages/blob/914d120da12fba458c020210727831c31bd71041/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** | https://github.com/flutter/packages/blob/cd7b93532e5cb605a42735e20f1de70fc00adae7/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. --- .../bench_pageview_scroll_linethrough.dart | 2 +- .../shrine/supplemental/product_card.dart | 3 +- .../flutter_gallery/lib/gallery/app.dart | 8 +- .../flutter_gallery/lib/gallery/home.dart | 3 +- .../flutter_gallery/lib/gallery/options.dart | 3 +- dev/manual_tests/lib/density.dart | 17 +- .../lib/action_chip_template.dart | 2 +- dev/tools/gen_defaults/lib/chip_template.dart | 2 +- .../lib/filter_chip_template.dart | 2 +- .../gen_defaults/lib/input_chip_template.dart | 2 +- .../material/app_bar/sliver_app_bar.1.dart | 2 +- .../material/app_bar/sliver_app_bar.4.dart | 2 +- .../time_picker/show_time_picker.0.dart | 3 +- .../flutter/lib/fix_data/fix_painting.yaml | 88 ++++++ .../flutter/lib/fix_data/fix_rendering.yaml | 44 +++ .../fix_data/fix_widgets/fix_media_query.yaml | 65 ++++ .../fix_data/fix_widgets/fix_rich_text.yaml | 43 +++ packages/flutter/lib/painting.dart | 1 + .../lib/src/cupertino/bottom_tab_bar.dart | 11 +- .../lib/src/cupertino/date_picker.dart | 16 +- .../flutter/lib/src/cupertino/dialog.dart | 18 +- .../flutter/lib/src/cupertino/nav_bar.dart | 28 +- .../lib/src/cupertino/page_scaffold.dart | 13 +- .../lib/src/cupertino/search_field.dart | 3 +- .../lib/src/cupertino/tab_scaffold.dart | 13 +- .../flutter/lib/src/material/action_chip.dart | 2 +- .../flutter/lib/src/material/app_bar.dart | 39 +-- .../src/material/bottom_navigation_bar.dart | 7 +- .../lib/src/material/button_style_button.dart | 15 +- packages/flutter/lib/src/material/chip.dart | 4 +- .../flutter/lib/src/material/choice_chip.dart | 2 +- .../lib/src/material/circle_avatar.dart | 7 +- .../flutter/lib/src/material/date_picker.dart | 24 +- packages/flutter/lib/src/material/dialog.dart | 4 +- .../flutter/lib/src/material/dropdown.dart | 3 +- .../lib/src/material/elevated_button.dart | 8 +- .../lib/src/material/filled_button.dart | 10 +- .../flutter/lib/src/material/filter_chip.dart | 2 +- .../flutter/lib/src/material/input_chip.dart | 2 +- .../lib/src/material/input_decorator.dart | 2 +- .../lib/src/material/navigation_bar.dart | 64 +--- .../lib/src/material/outlined_button.dart | 6 +- .../lib/src/material/selectable_text.dart | 35 ++- packages/flutter/lib/src/material/slider.dart | 4 +- .../flutter/lib/src/material/text_button.dart | 8 +- .../flutter/lib/src/material/time_picker.dart | 16 +- .../flutter/lib/src/painting/inline_span.dart | 8 +- .../lib/src/painting/text_painter.dart | 81 ++++- .../flutter/lib/src/painting/text_scaler.dart | 151 ++++++++++ .../flutter/lib/src/painting/text_span.dart | 7 +- .../flutter/lib/src/painting/text_style.dart | 41 ++- .../flutter/lib/src/rendering/editable.dart | 37 ++- .../flutter/lib/src/rendering/paragraph.dart | 45 ++- packages/flutter/lib/src/widgets/basic.dart | 41 ++- .../lib/src/widgets/editable_text.dart | 63 +++- .../flutter/lib/src/widgets/media_query.dart | 207 ++++++++++++- packages/flutter/lib/src/widgets/text.dart | 44 ++- .../flutter/lib/src/widgets/widget_span.dart | 39 ++- .../cupertino/material/tab_scaffold_test.dart | 4 +- .../flutter/test/cupertino/nav_bar_test.dart | 4 +- .../flutter/test/cupertino/scaffold_test.dart | 2 +- .../test/cupertino/tab_scaffold_test.dart | 4 +- .../flutter/test/material/app_bar_test.dart | 30 ++ packages/flutter/test/material/app_test.dart | 7 +- .../flutter/test/material/theme_test.dart | 3 +- .../test/painting/text_painter_test.dart | 8 +- .../test/painting/text_scaler_test.dart | 37 +++ .../test/painting/text_style_test.dart | 4 +- .../test/painting/widget_span_test.dart | 28 -- .../flutter/test/rendering/editable_test.dart | 7 +- .../test/rendering/paragraph_test.dart | 4 +- .../test/widgets/media_query_test.dart | 132 +++++---- .../flutter/test/widgets/rich_text_test.dart | 4 +- .../test/widgets/selectable_text_test.dart | 4 +- ...xt_scaler_backward_compatibility_test.dart | 278 ++++++++++++++++++ packages/flutter/test/widgets/text_test.dart | 12 +- .../test/widgets/widget_span_test.dart | 77 +++++ .../flutter/test_fixes/painting/painting.dart | 11 + .../test_fixes/painting/painting.dart.expect | 11 + .../test_fixes/rendering/rendering.dart | 6 + .../rendering/rendering.dart.expect | 6 + .../test_fixes/widgets/media_query.dart | 13 + .../widgets/media_query.dart.expect | 13 + .../flutter/test_fixes/widgets/rich_text.dart | 11 + .../test_fixes/widgets/rich_text.dart.expect | 11 + 85 files changed, 1696 insertions(+), 457 deletions(-) create mode 100644 packages/flutter/lib/fix_data/fix_widgets/fix_media_query.yaml create mode 100644 packages/flutter/lib/fix_data/fix_widgets/fix_rich_text.yaml create mode 100644 packages/flutter/lib/src/painting/text_scaler.dart create mode 100644 packages/flutter/test/painting/text_scaler_test.dart delete mode 100644 packages/flutter/test/painting/widget_span_test.dart create mode 100644 packages/flutter/test/widgets/text_scaler_backward_compatibility_test.dart create mode 100644 packages/flutter/test/widgets/widget_span_test.dart create mode 100644 packages/flutter/test_fixes/widgets/media_query.dart create mode 100644 packages/flutter/test_fixes/widgets/media_query.dart.expect create mode 100644 packages/flutter/test_fixes/widgets/rich_text.dart create mode 100644 packages/flutter/test_fixes/widgets/rich_text.dart.expect diff --git a/dev/benchmarks/macrobenchmarks/lib/src/web/bench_pageview_scroll_linethrough.dart b/dev/benchmarks/macrobenchmarks/lib/src/web/bench_pageview_scroll_linethrough.dart index c605072714..f5ee8dd906 100644 --- a/dev/benchmarks/macrobenchmarks/lib/src/web/bench_pageview_scroll_linethrough.dart +++ b/dev/benchmarks/macrobenchmarks/lib/src/web/bench_pageview_scroll_linethrough.dart @@ -95,7 +95,7 @@ class _CustomPainter extends CustomPainter { yPosition = viewPadding; _textPainter.textDirection = TextDirection.ltr; _textPainter.textWidthBasis = TextWidthBasis.longestLine; - _textPainter.textScaleFactor = 1; + _textPainter.textScaler = TextScaler.noScaling; const TextStyle textStyle = TextStyle(color: Colors.black87, fontSize: 13, fontFamily: 'Roboto'); diff --git a/dev/integration_tests/flutter_gallery/lib/demo/shrine/supplemental/product_card.dart b/dev/integration_tests/flutter_gallery/lib/demo/shrine/supplemental/product_card.dart index b5d4083d9c..5a32001fed 100644 --- a/dev/integration_tests/flutter_gallery/lib/demo/shrine/supplemental/product_card.dart +++ b/dev/integration_tests/flutter_gallery/lib/demo/shrine/supplemental/product_card.dart @@ -52,7 +52,8 @@ class ProductCard extends StatelessWidget { child: imageWidget, ), SizedBox( - height: kTextBoxHeight * MediaQuery.of(context).textScaleFactor, + // ignore: deprecated_member_use, https://github.com/flutter/flutter/issues/128825 + height: kTextBoxHeight * MediaQuery.textScalerOf(context).textScaleFactor, width: 121.0, child: Column( mainAxisAlignment: MainAxisAlignment.end, diff --git a/dev/integration_tests/flutter_gallery/lib/gallery/app.dart b/dev/integration_tests/flutter_gallery/lib/gallery/app.dart index 788c48d7a1..e2d8f0fb34 100644 --- a/dev/integration_tests/flutter_gallery/lib/gallery/app.dart +++ b/dev/integration_tests/flutter_gallery/lib/gallery/app.dart @@ -104,10 +104,10 @@ class _GalleryAppState extends State { Widget _applyTextScaleFactor(Widget child) { return Builder( builder: (BuildContext context) { - return MediaQuery( - data: MediaQuery.of(context).copyWith( - textScaleFactor: _options!.textScaleFactor!.scale, - ), + final double? textScaleFactor = _options!.textScaleFactor!.scale; + return MediaQuery.withClampedTextScaling( + minScaleFactor: textScaleFactor ?? 0.0, + maxScaleFactor: textScaleFactor ?? double.infinity, child: child, ); }, diff --git a/dev/integration_tests/flutter_gallery/lib/gallery/home.dart b/dev/integration_tests/flutter_gallery/lib/gallery/home.dart index ebbce5404e..c661ce6448 100644 --- a/dev/integration_tests/flutter_gallery/lib/gallery/home.dart +++ b/dev/integration_tests/flutter_gallery/lib/gallery/home.dart @@ -178,7 +178,8 @@ class _DemoItem extends StatelessWidget { Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); final bool isDark = theme.brightness == Brightness.dark; - final double textScaleFactor = MediaQuery.textScaleFactorOf(context); + // ignore: deprecated_member_use, https://github.com/flutter/flutter/issues/128825 + final double textScaleFactor = MediaQuery.textScalerOf(context).textScaleFactor; return RawMaterialButton( splashColor: theme.primaryColor.withOpacity(0.12), highlightColor: Colors.transparent, diff --git a/dev/integration_tests/flutter_gallery/lib/gallery/options.dart b/dev/integration_tests/flutter_gallery/lib/gallery/options.dart index c1c4b8314e..53b542ff4e 100644 --- a/dev/integration_tests/flutter_gallery/lib/gallery/options.dart +++ b/dev/integration_tests/flutter_gallery/lib/gallery/options.dart @@ -100,7 +100,8 @@ class _OptionsItem extends StatelessWidget { @override Widget build(BuildContext context) { - final double textScaleFactor = MediaQuery.textScaleFactorOf(context); + // ignore: deprecated_member_use, https://github.com/flutter/flutter/issues/128825 + final double textScaleFactor = MediaQuery.textScalerOf(context).textScaleFactor; return MergeSemantics( child: Container( diff --git a/dev/manual_tests/lib/density.dart b/dev/manual_tests/lib/density.dart index 02e252e4da..783b7d0108 100644 --- a/dev/manual_tests/lib/density.dart +++ b/dev/manual_tests/lib/density.dart @@ -621,14 +621,17 @@ class _MyHomePageState extends State { data: Theme.of(context).copyWith(visualDensity: _model.density), child: Directionality( textDirection: _model.rtl ? TextDirection.rtl : TextDirection.ltr, - child: MediaQuery( - data: MediaQuery.of(context).copyWith(textScaleFactor: _model.size), - child: SizedBox.expand( - child: ListView( - children: tiles, + child: Builder(builder: (BuildContext context) { + final MediaQueryData mediaQueryData = MediaQuery.of(context); + return MediaQuery( + data: mediaQueryData.copyWith(textScaler: TextScaler.linear(_model.size)), + child: SizedBox.expand( + child: ListView( + children: tiles, + ), ), - ), - ), + ); + }), ), ), ), diff --git a/dev/tools/gen_defaults/lib/action_chip_template.dart b/dev/tools/gen_defaults/lib/action_chip_template.dart index 54027c13d7..ade6164e63 100644 --- a/dev/tools/gen_defaults/lib/action_chip_template.dart +++ b/dev/tools/gen_defaults/lib/action_chip_template.dart @@ -91,7 +91,7 @@ class _${blockName}DefaultsM3 extends ChipThemeData { EdgeInsetsGeometry? get labelPadding => EdgeInsets.lerp( const EdgeInsets.symmetric(horizontal: 8.0), const EdgeInsets.symmetric(horizontal: 4.0), - clampDouble(MediaQuery.textScaleFactorOf(context) - 1.0, 0.0, 1.0), + clampDouble(MediaQuery.textScalerOf(context).textScaleFactor - 1.0, 0.0, 1.0), )!; } '''; diff --git a/dev/tools/gen_defaults/lib/chip_template.dart b/dev/tools/gen_defaults/lib/chip_template.dart index 8d9c05b7cc..4d9383399d 100644 --- a/dev/tools/gen_defaults/lib/chip_template.dart +++ b/dev/tools/gen_defaults/lib/chip_template.dart @@ -70,7 +70,7 @@ class _${blockName}DefaultsM3 extends ChipThemeData { EdgeInsetsGeometry? get labelPadding => EdgeInsets.lerp( const EdgeInsets.symmetric(horizontal: 8.0), const EdgeInsets.symmetric(horizontal: 4.0), - clampDouble(MediaQuery.textScaleFactorOf(context) - 1.0, 0.0, 1.0), + clampDouble(MediaQuery.textScalerOf(context).textScaleFactor - 1.0, 0.0, 1.0), )!; } '''; diff --git a/dev/tools/gen_defaults/lib/filter_chip_template.dart b/dev/tools/gen_defaults/lib/filter_chip_template.dart index 6609613cde..d13cba9cff 100644 --- a/dev/tools/gen_defaults/lib/filter_chip_template.dart +++ b/dev/tools/gen_defaults/lib/filter_chip_template.dart @@ -108,7 +108,7 @@ class _${blockName}DefaultsM3 extends ChipThemeData { EdgeInsetsGeometry? get labelPadding => EdgeInsets.lerp( const EdgeInsets.symmetric(horizontal: 8.0), const EdgeInsets.symmetric(horizontal: 4.0), - clampDouble(MediaQuery.textScaleFactorOf(context) - 1.0, 0.0, 1.0), + clampDouble(MediaQuery.textScalerOf(context).textScaleFactor - 1.0, 0.0, 1.0), )!; } '''; diff --git a/dev/tools/gen_defaults/lib/input_chip_template.dart b/dev/tools/gen_defaults/lib/input_chip_template.dart index 245a171b90..529113cbbf 100644 --- a/dev/tools/gen_defaults/lib/input_chip_template.dart +++ b/dev/tools/gen_defaults/lib/input_chip_template.dart @@ -85,7 +85,7 @@ class _${blockName}DefaultsM3 extends ChipThemeData { EdgeInsetsGeometry? get labelPadding => EdgeInsets.lerp( const EdgeInsets.symmetric(horizontal: 8.0), const EdgeInsets.symmetric(horizontal: 4.0), - clampDouble(MediaQuery.textScaleFactorOf(context) - 1.0, 0.0, 1.0), + clampDouble(MediaQuery.textScalerOf(context).textScaleFactor - 1.0, 0.0, 1.0), )!; } '''; diff --git a/examples/api/lib/material/app_bar/sliver_app_bar.1.dart b/examples/api/lib/material/app_bar/sliver_app_bar.1.dart index 9d7ad116fc..46b41d8180 100644 --- a/examples/api/lib/material/app_bar/sliver_app_bar.1.dart +++ b/examples/api/lib/material/app_bar/sliver_app_bar.1.dart @@ -63,7 +63,7 @@ class _SliverAppBarExampleState extends State { color: index.isOdd ? Colors.white : Colors.black12, height: 100.0, child: Center( - child: Text('$index', textScaleFactor: 5), + child: Text('$index', textScaler: const TextScaler.linear(5)), ), ); }, diff --git a/examples/api/lib/material/app_bar/sliver_app_bar.4.dart b/examples/api/lib/material/app_bar/sliver_app_bar.4.dart index 769c970fa1..77d2773988 100644 --- a/examples/api/lib/material/app_bar/sliver_app_bar.4.dart +++ b/examples/api/lib/material/app_bar/sliver_app_bar.4.dart @@ -51,7 +51,7 @@ class _StretchableSliverAppBarState extends State { color: index.isOdd ? Colors.white : Colors.black12, height: 100.0, child: Center( - child: Text('$index', textScaleFactor: 5), + child: Text('$index', textScaler: const TextScaler.linear(5.0)), ), ); }, diff --git a/examples/api/lib/material/time_picker/show_time_picker.0.dart b/examples/api/lib/material/time_picker/show_time_picker.0.dart index 6e7b9cfee9..d7d05702d6 100644 --- a/examples/api/lib/material/time_picker/show_time_picker.0.dart +++ b/examples/api/lib/material/time_picker/show_time_picker.0.dart @@ -129,7 +129,8 @@ class _TimePickerOptionsState extends State { gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent( maxCrossAxisExtent: 350, mainAxisSpacing: 4, - mainAxisExtent: 200 * MediaQuery.textScaleFactorOf(context), + // ignore: deprecated_member_use, https://github.com/flutter/flutter/issues/128825 + mainAxisExtent: 200 * MediaQuery.textScalerOf(context).textScaleFactor, crossAxisSpacing: 4, ), children: [ diff --git a/packages/flutter/lib/fix_data/fix_painting.yaml b/packages/flutter/lib/fix_data/fix_painting.yaml index 0b88041a10..b83d86f28c 100644 --- a/packages/flutter/lib/fix_data/fix_painting.yaml +++ b/packages/flutter/lib/fix_data/fix_painting.yaml @@ -18,6 +18,94 @@ # * Fixes in this file are from the Painting library. * version: 1 transforms: + # Change made in https://github.com/flutter/flutter/pull/128522 + - title: "Migrate to 'textScaler'" + date: 2023-06-09 + element: + uris: [ 'painting.dart' ] + method: 'computeMaxIntrinsicWidth' + inClass: 'TextPainter' + changes: + - kind: 'addParameter' + index: 4 + name: 'textScaler' + style: optional_named + argumentValue: + expression: 'TextScaler.linear({% textScaleFactor %})' + requiredIf: "textScaleFactor != ''" + - kind: 'removeParameter' + name: 'textScaleFactor' + variables: + textScaleFactor: + kind: 'fragment' + value: 'arguments[textScaleFactor]' + + # Change made in https://github.com/flutter/flutter/pull/128522 + - title: "Migrate to 'textScaler'" + date: 2023-06-09 + element: + uris: [ 'painting.dart' ] + method: 'computeWidth' + inClass: 'TextPainter' + changes: + - kind: 'addParameter' + index: 4 + name: 'textScaler' + style: optional_named + argumentValue: + expression: 'TextScaler.linear({% textScaleFactor %})' + requiredIf: "textScaleFactor != ''" + - kind: 'removeParameter' + name: 'textScaleFactor' + variables: + textScaleFactor: + kind: 'fragment' + value: 'arguments[textScaleFactor]' + + # Change made in https://github.com/flutter/flutter/pull/128522 + - title: "Migrate to 'textScaler'" + date: 2023-06-09 + element: + uris: [ 'painting.dart' ] + constructor: '' + inClass: 'TextPainter' + changes: + - kind: 'addParameter' + index: 0 + name: 'textScaler' + style: optional_named + argumentValue: + expression: 'TextScaler.linear({% textScaleFactor %})' + requiredIf: "textScaleFactor != ''" + - kind: 'removeParameter' + name: 'textScaleFactor' + variables: + textScaleFactor: + kind: 'fragment' + value: 'arguments[textScaleFactor]' + + # Change made in https://github.com/flutter/flutter/pull/128522 + - title: "Migrate to 'textScaler'" + date: 2023-06-09 + element: + uris: [ 'painting.dart' ] + method: 'getTextStyle' + inClass: 'TextStyle' + changes: + - kind: 'addParameter' + index: 0 + name: 'textScaler' + style: optional_named + argumentValue: + expression: 'TextScaler.linear({% textScaleFactor %})' + requiredIf: "textScaleFactor != ''" + - kind: 'removeParameter' + name: 'textScaleFactor' + variables: + textScaleFactor: + kind: 'fragment' + value: 'arguments[textScaleFactor]' + # Changes made in https://github.com/flutter/flutter/pull/121152 - title: "Rename to 'fromViewPadding'" date: 2022-02-21 diff --git a/packages/flutter/lib/fix_data/fix_rendering.yaml b/packages/flutter/lib/fix_data/fix_rendering.yaml index efc56a8bc4..75ae29fc56 100644 --- a/packages/flutter/lib/fix_data/fix_rendering.yaml +++ b/packages/flutter/lib/fix_data/fix_rendering.yaml @@ -18,6 +18,50 @@ # * Fixes in this file are from the Rendering library. * version: 1 transforms: + # Change made in https://github.com/flutter/flutter/pull/128522 + - title: "Migrate to 'textScaler'" + date: 2023-06-09 + element: + uris: [ 'rendering.dart' ] + constructor: '' + inClass: 'RenderParagraph' + changes: + - kind: 'addParameter' + index: 5 + name: 'textScaler' + style: optional_named + argumentValue: + expression: 'TextScaler.linear({% textScaleFactor %})' + requiredIf: "textScaleFactor != ''" + - kind: 'removeParameter' + name: 'textScaleFactor' + variables: + textScaleFactor: + kind: 'fragment' + value: 'arguments[textScaleFactor]' + + # Change made in https://github.com/flutter/flutter/pull/128522 + - title: "Migrate to 'textScaler'" + date: 2023-06-09 + element: + uris: [ 'rendering.dart' ] + constructor: '' + inClass: 'RenderEditable' + changes: + - kind: 'addParameter' + index: 15 + name: 'textScaler' + style: optional_named + argumentValue: + expression: 'TextScaler.linear({% textScaleFactor %})' + requiredIf: "textScaleFactor != ''" + - kind: 'removeParameter' + name: 'textScaleFactor' + variables: + textScaleFactor: + kind: 'fragment' + value: 'arguments[textScaleFactor]' + # Changes made in https://github.com/flutter/flutter/pull/66305 - title: "Migrate to 'clipBehavior'" date: 2020-09-22 diff --git a/packages/flutter/lib/fix_data/fix_widgets/fix_media_query.yaml b/packages/flutter/lib/fix_data/fix_widgets/fix_media_query.yaml new file mode 100644 index 0000000000..c7092e9311 --- /dev/null +++ b/packages/flutter/lib/fix_data/fix_widgets/fix_media_query.yaml @@ -0,0 +1,65 @@ +# 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. + +# For details regarding the *Flutter Fix* feature, see +# https://flutter.dev/docs/development/tools/flutter-fix + +# Please add new fixes to the top of the file, separated by one blank line +# from other fixes. In a comment, include a link to the PR where the change +# requiring the fix was made. + +# Every fix must be tested. See the flutter/packages/flutter/test_fixes/README.md +# file for instructions on testing these data driven fixes. + +# For documentation about this file format, see +# https://dart.dev/go/data-driven-fixes. + +# * Fixes in this file are for MediaQuery and MediaQueryData from the widgets library. * +version: 1 +transforms: + # Change made in https://github.com/flutter/flutter/pull/128522 + - title: "Migrate to 'textScaler'" + date: 2023-06-09 + element: + uris: [ 'widgets.dart', 'material.dart', 'cupertino.dart' ] + method: 'copyWith' + inClass: 'MediaQueryData' + changes: + - kind: 'addParameter' + index: 3 + name: 'textScaler' + style: optional_named + argumentValue: + expression: 'TextScaler.linear({% textScaleFactor %})' + requiredIf: "textScaleFactor != ''" + - kind: 'removeParameter' + name: 'textScaleFactor' + variables: + textScaleFactor: + kind: 'fragment' + value: 'arguments[textScaleFactor]' + + # Change made in https://github.com/flutter/flutter/pull/128522 + - title: "Migrate to 'textScaler'" + date: 2023-06-09 + element: + uris: [ 'widgets.dart', 'material.dart', 'cupertino.dart' ] + constructor: '' + inClass: 'MediaQueryData' + changes: + - kind: 'addParameter' + index: 3 + name: 'textScaler' + style: optional_named + argumentValue: + expression: 'TextScaler.linear({% textScaleFactor %})' + requiredIf: "textScaleFactor != ''" + - kind: 'removeParameter' + name: 'textScaleFactor' + variables: + textScaleFactor: + kind: 'fragment' + value: 'arguments[textScaleFactor]' + +# Before adding a new fix: read instructions at the top of this file. diff --git a/packages/flutter/lib/fix_data/fix_widgets/fix_rich_text.yaml b/packages/flutter/lib/fix_data/fix_widgets/fix_rich_text.yaml new file mode 100644 index 0000000000..1f3f5cc014 --- /dev/null +++ b/packages/flutter/lib/fix_data/fix_widgets/fix_rich_text.yaml @@ -0,0 +1,43 @@ +# 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. + +# For details regarding the *Flutter Fix* feature, see +# https://flutter.dev/docs/development/tools/flutter-fix + +# Please add new fixes to the top of the file, separated by one blank line +# from other fixes. In a comment, include a link to the PR where the change +# requiring the fix was made. + +# Every fix must be tested. See the flutter/packages/flutter/test_fixes/README.md +# file for instructions on testing these data driven fixes. + +# For documentation about this file format, see +# https://dart.dev/go/data-driven-fixes. + +# * Fixes in this file are for RichText from the widgets library. * +version: 1 +transforms: + # Change made in https://github.com/flutter/flutter/pull/128522 + - title: "Migrate to 'textScaler'" + date: 2023-06-09 + element: + uris: [ 'widgets.dart', 'material.dart', 'cupertino.dart' ] + constructor: '' + inClass: 'RichText' + changes: + - kind: 'addParameter' + index: 7 + name: 'textScaler' + style: optional_named + argumentValue: + expression: 'TextScaler.linear({% textScaleFactor %})' + requiredIf: "textScaleFactor != ''" + - kind: 'removeParameter' + name: 'textScaleFactor' + variables: + textScaleFactor: + kind: 'fragment' + value: 'arguments[textScaleFactor]' + +# Before adding a new fix: read instructions at the top of this file. diff --git a/packages/flutter/lib/painting.dart b/packages/flutter/lib/painting.dart index 8a78b6bf4a..2fa89c23cf 100644 --- a/packages/flutter/lib/painting.dart +++ b/packages/flutter/lib/painting.dart @@ -60,5 +60,6 @@ export 'src/painting/stadium_border.dart'; export 'src/painting/star_border.dart'; export 'src/painting/strut_style.dart'; export 'src/painting/text_painter.dart'; +export 'src/painting/text_scaler.dart'; export 'src/painting/text_span.dart'; export 'src/painting/text_style.dart'; diff --git a/packages/flutter/lib/src/cupertino/bottom_tab_bar.dart b/packages/flutter/lib/src/cupertino/bottom_tab_bar.dart index 4bdbe86a99..6d920abff9 100644 --- a/packages/flutter/lib/src/cupertino/bottom_tab_bar.dart +++ b/packages/flutter/lib/src/cupertino/bottom_tab_bar.dart @@ -37,13 +37,10 @@ const Color _kDefaultTabBarInactiveColor = CupertinoColors.inactiveGray; /// If the given [backgroundColor]'s opacity is not 1.0 (which is the case by /// default), it will produce a blurring effect to the content behind it. /// -/// When used as [CupertinoTabScaffold.tabBar], by default [CupertinoTabBar] has -/// its text scale factor set to 1.0 and does not respond to text scale factor -/// changes from the operating system, to match the native iOS behavior. To override -/// this behavior, wrap each of the `navigationBar`'s components inside a [MediaQuery] -/// with the desired [MediaQueryData.textScaleFactor] value. The text scale factor -/// value from the operating system can be retrieved in many ways, such as querying -/// [MediaQuery.textScaleFactorOf] against [CupertinoApp]'s [BuildContext]. +/// When used as [CupertinoTabScaffold.tabBar], by default [CupertinoTabBar] +/// disables text scaling to match the native iOS behavior. To override +/// this behavior, wrap each of the `navigationBar`'s components inside a +/// [MediaQuery] with the desired [TextScaler]. /// /// {@tool dartpad} /// This example shows a [CupertinoTabBar] placed in a [CupertinoTabScaffold]. diff --git a/packages/flutter/lib/src/cupertino/date_picker.dart b/packages/flutter/lib/src/cupertino/date_picker.dart index 1b43e697bc..693b4069a3 100644 --- a/packages/flutter/lib/src/cupertino/date_picker.dart +++ b/packages/flutter/lib/src/cupertino/date_picker.dart @@ -1097,8 +1097,7 @@ class _CupertinoDatePickerDateTimeState extends State { final double maxPickerWidth = totalColumnWidths > _kPickerWidth ? totalColumnWidths : _kPickerWidth; - return MediaQuery( - data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0), + return MediaQuery.withNoTextScaling( child: DefaultTextStyle.merge( style: _kDefaultPickerTextStyle, child: CustomMultiChildLayout( @@ -1487,8 +1486,7 @@ class _CupertinoDatePickerDateState extends State { final double maxPickerWidth = totalColumnWidths > _kPickerWidth ? totalColumnWidths : _kPickerWidth; - return MediaQuery( - data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0), + return MediaQuery.withNoTextScaling( child: DefaultTextStyle.merge( style: _kDefaultPickerTextStyle, child: CustomMultiChildLayout( @@ -1802,8 +1800,7 @@ class _CupertinoDatePickerMonthYearState extends State { final double maxPickerWidth = totalColumnWidths > _kPickerWidth ? totalColumnWidths : _kPickerWidth; - return MediaQuery( - data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0), + return MediaQuery.withNoTextScaling( child: DefaultTextStyle.merge( style: _kDefaultPickerTextStyle, child: CustomMultiChildLayout( @@ -2502,10 +2499,9 @@ class _CupertinoTimerPickerState extends State { ]; } final CupertinoThemeData themeData = CupertinoTheme.of(context); - return MediaQuery( - // The native iOS picker's text scaling is fixed, so we will also fix it - // as well in our picker. - data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0), + // The native iOS picker's text scaling is fixed, so we will also fix it + // as well in our picker. + return MediaQuery.withNoTextScaling( child: CupertinoTheme( data: themeData.copyWith( textTheme: themeData.textTheme.copyWith( diff --git a/packages/flutter/lib/src/cupertino/dialog.dart b/packages/flutter/lib/src/cupertino/dialog.dart index 0cb4cf8adc..ef8c109360 100644 --- a/packages/flutter/lib/src/cupertino/dialog.dart +++ b/packages/flutter/lib/src/cupertino/dialog.dart @@ -149,7 +149,7 @@ const double _kMaxRegularTextScaleFactor = 1.4; // Accessibility mode on iOS is determined by the text scale factor that the // user has selected. bool _isInAccessibilityMode(BuildContext context) { - final double? factor = MediaQuery.maybeTextScaleFactorOf(context); + final double? factor = MediaQuery.maybeTextScalerOf(context)?.textScaleFactor; return factor != null && factor > _kMaxRegularTextScaleFactor; } @@ -257,7 +257,7 @@ class CupertinoAlertDialog extends StatelessWidget { final Curve insetAnimationCurve; Widget _buildContent(BuildContext context) { - final double textScaleFactor = MediaQuery.textScaleFactorOf(context); + final double textScaleFactor = MediaQuery.textScalerOf(context).textScaleFactor; final List children = [ if (title != null || content != null) @@ -317,14 +317,11 @@ class CupertinoAlertDialog extends StatelessWidget { Widget build(BuildContext context) { final CupertinoLocalizations localizations = CupertinoLocalizations.of(context); final bool isInAccessibilityMode = _isInAccessibilityMode(context); - final double textScaleFactor = MediaQuery.textScaleFactorOf(context); return CupertinoUserInterfaceLevel( data: CupertinoUserInterfaceLevelData.elevated, - child: MediaQuery( - data: MediaQuery.of(context).copyWith( - // iOS does not shrink dialog content below a 1.0 scale factor - textScaleFactor: math.max(textScaleFactor, 1.0), - ), + child: MediaQuery.withClampedTextScaling( + // iOS does not shrink dialog content below a 1.0 scale factor + minScaleFactor: 1.0, child: ScrollConfiguration( // A CupertinoScrollbar is built-in below. behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false), @@ -1633,7 +1630,7 @@ class CupertinoDialogAction extends StatelessWidget { bool get enabled => onPressed != null; double _calculatePadding(BuildContext context) { - return 8.0 * MediaQuery.textScaleFactorOf(context); + return 8.0 * MediaQuery.textScalerOf(context).textScaleFactor; } // Dialog action content shrinks to fit, up to a certain point, and if it still @@ -1649,12 +1646,11 @@ class CupertinoDialogAction extends StatelessWidget { final double dialogWidth = isInAccessibilityMode ? _kAccessibilityCupertinoDialogWidth : _kCupertinoDialogWidth; - final double textScaleFactor = MediaQuery.textScaleFactorOf(context); // The fontSizeRatio is the ratio of the current text size (including any // iOS scale factor) vs the minimum text size that we allow in action // buttons. This ratio information is used to automatically scale down action // button text to fit the available space. - final double fontSizeRatio = (textScaleFactor * textStyle.fontSize!) / _kDialogMinButtonFontSize; + final double fontSizeRatio = MediaQuery.textScalerOf(context).scale(textStyle.fontSize!) / _kDialogMinButtonFontSize; final double padding = _calculatePadding(context); return IntrinsicHeight( diff --git a/packages/flutter/lib/src/cupertino/nav_bar.dart b/packages/flutter/lib/src/cupertino/nav_bar.dart index f33ea8d95c..9c2d472f15 100644 --- a/packages/flutter/lib/src/cupertino/nav_bar.dart +++ b/packages/flutter/lib/src/cupertino/nav_bar.dart @@ -229,12 +229,9 @@ bool _isTransitionable(BuildContext context) { /// behavior for multiple navigation bars per route. /// /// When used in a [CupertinoPageScaffold], [CupertinoPageScaffold.navigationBar] -/// has its text scale factor set to 1.0 and does not respond to text scale factor -/// changes from the operating system, to match the native iOS behavior. To override -/// this behavior, wrap each of the `navigationBar`'s components inside a [MediaQuery] -/// with the desired [MediaQueryData.textScaleFactor] value. The text scale factor -/// value from the operating system can be retrieved in many ways, such as querying -/// [MediaQuery.textScaleFactorOf] against [CupertinoApp]'s [BuildContext]. +/// disables text scaling to match the native iOS behavior. To override +/// this behavior, wrap each of the `navigationBar`'s components inside a +/// [MediaQuery] with the desired [TextScaler]. /// /// {@tool dartpad} /// This example shows a [CupertinoNavigationBar] placed in a [CupertinoPageScaffold]. @@ -555,13 +552,10 @@ class _CupertinoNavigationBarState extends State { /// Use [transitionBetweenRoutes] or [heroTag] to customize the transition /// behavior for multiple navigation bars per route. /// -/// [CupertinoSliverNavigationBar] has its text scale factor set to 1.0 by default -/// and does not respond to text scale factor changes from the operating system, -/// to match the native iOS behavior. To override this behavior, wrap each of the +/// [CupertinoSliverNavigationBar] by default disables text scaling to match the +/// native iOS behavior. To override this behavior, wrap each of the /// [CupertinoSliverNavigationBar]'s components inside a [MediaQuery] with the -/// desired [MediaQueryData.textScaleFactor] value. The text scale factor value -/// from the operating system can be retrieved in many ways, such as querying -/// [MediaQuery.textScaleFactorOf] against [CupertinoApp]'s [BuildContext]. +/// desired [TextScaler]. /// /// The [stretch] parameter determines whether the nav bar should stretch to /// fill the over-scroll area. The nav bar can still expand and contract as the @@ -741,8 +735,7 @@ class _CupertinoSliverNavigationBarState extends State { top: 0.0, left: 0.0, right: 0.0, - child: MediaQuery( - data: existingMediaQuery.copyWith(textScaleFactor: 1), + child: MediaQuery.withNoTextScaling( child: widget.navigationBar!, ), ), diff --git a/packages/flutter/lib/src/cupertino/search_field.dart b/packages/flutter/lib/src/cupertino/search_field.dart index ac868801bc..0748feb13f 100644 --- a/packages/flutter/lib/src/cupertino/search_field.dart +++ b/packages/flutter/lib/src/cupertino/search_field.dart @@ -400,8 +400,7 @@ class _CupertinoSearchTextFieldState extends State // The icon size will be scaled by a factor of the accessibility text scale, // to follow the behavior of `UISearchTextField`. - final double scaledIconSize = - MediaQuery.textScaleFactorOf(context) * widget.itemSize; + final double scaledIconSize = MediaQuery.textScalerOf(context).textScaleFactor * widget.itemSize; // If decoration was not provided, create a decoration with the provided // background color and border radius. diff --git a/packages/flutter/lib/src/cupertino/tab_scaffold.dart b/packages/flutter/lib/src/cupertino/tab_scaffold.dart index 056cf18ef9..8bd129a7eb 100644 --- a/packages/flutter/lib/src/cupertino/tab_scaffold.dart +++ b/packages/flutter/lib/src/cupertino/tab_scaffold.dart @@ -158,13 +158,9 @@ class CupertinoTabScaffold extends StatefulWidget { /// If translucent, the main content may slide behind it. /// Otherwise, the main content's bottom margin will be offset by its height. /// - /// By default [tabBar] has its text scale factor set to 1.0 and does not - /// respond to text scale factor changes from the operating system, to match - /// the native iOS behavior. To override this behavior, wrap each of the [tabBar]'s - /// items inside a [MediaQuery] with the desired [MediaQueryData.textScaleFactor] - /// value. The text scale factor value from the operating system can be retrieved - /// int many ways, such as querying [MediaQuery.textScaleFactorOf] against - /// [CupertinoApp]'s [BuildContext]. + /// By default [tabBar] disables text scaling to match the native iOS behavior. + /// To override this behavior, wrap each of the [tabBar]'s items inside a + /// [MediaQuery] with the desired [TextScaler]. /// /// Must not be null. final CupertinoTabBar tabBar; @@ -361,8 +357,7 @@ class _CupertinoTabScaffoldState extends State with Restor children: [ // The main content being at the bottom is added to the stack first. content, - MediaQuery( - data: existingMediaQuery.copyWith(textScaleFactor: 1), + MediaQuery.withNoTextScaling( child: Align( alignment: Alignment.bottomCenter, // Override the tab bar's currentIndex to the current tab and hook in diff --git a/packages/flutter/lib/src/material/action_chip.dart b/packages/flutter/lib/src/material/action_chip.dart index 725570fd56..142fc4058b 100644 --- a/packages/flutter/lib/src/material/action_chip.dart +++ b/packages/flutter/lib/src/material/action_chip.dart @@ -311,7 +311,7 @@ class _ActionChipDefaultsM3 extends ChipThemeData { EdgeInsetsGeometry? get labelPadding => EdgeInsets.lerp( const EdgeInsets.symmetric(horizontal: 8.0), const EdgeInsets.symmetric(horizontal: 4.0), - clampDouble(MediaQuery.textScaleFactorOf(context) - 1.0, 0.0, 1.0), + clampDouble(MediaQuery.textScalerOf(context).textScaleFactor - 1.0, 0.0, 1.0), )!; } diff --git a/packages/flutter/lib/src/material/app_bar.dart b/packages/flutter/lib/src/material/app_bar.dart index d0aabc3ca0..c94bfa5e3c 100644 --- a/packages/flutter/lib/src/material/app_bar.dart +++ b/packages/flutter/lib/src/material/app_bar.dart @@ -951,22 +951,13 @@ class _AppBarState extends State { Widget? title = widget.title; if (title != null) { - bool? namesRoute; - switch (theme.platform) { - case TargetPlatform.android: - case TargetPlatform.fuchsia: - case TargetPlatform.linux: - case TargetPlatform.windows: - namesRoute = true; - case TargetPlatform.iOS: - case TargetPlatform.macOS: - break; - } - title = _AppBarTitleBox(child: title); if (!widget.excludeHeaderSemantics) { title = Semantics( - namesRoute: namesRoute, + namesRoute: switch (theme.platform) { + TargetPlatform.android || TargetPlatform.fuchsia || TargetPlatform.linux || TargetPlatform.windows => true, + TargetPlatform.iOS || TargetPlatform.macOS => null, + }, header: true, child: title, ); @@ -982,16 +973,9 @@ class _AppBarState extends State { // Set maximum text scale factor to [_kMaxTitleTextScaleFactor] for the // title to keep the visual hierarchy the same even with larger font // sizes. To opt out, wrap the [title] widget in a [MediaQuery] widget - // with [MediaQueryData.textScaleFactor] set to - // `MediaQuery.textScaleFactorOf(context)`. - final MediaQueryData mediaQueryData = MediaQuery.of(context); - title = MediaQuery( - data: mediaQueryData.copyWith( - textScaleFactor: math.min( - mediaQueryData.textScaleFactor, - _kMaxTitleTextScaleFactor, - ), - ), + // with a different `TextScaler`. + title = MediaQuery.withClampedTextScaling( + maxScaleFactor: _kMaxTitleTextScaleFactor, child: title, ); } @@ -2098,7 +2082,6 @@ class _ScrollUnderFlexibleSpace extends StatelessWidget { Widget build(BuildContext context) { late final AppBarTheme appBarTheme = AppBarTheme.of(context); late final AppBarTheme defaults = Theme.of(context).useMaterial3 ? _AppBarDefaultsM3(context) : _AppBarDefaultsM2(context); - final double textScaleFactor = math.min(MediaQuery.textScaleFactorOf(context), _kMaxTitleTextScaleFactor); // TODO(tahatesser): Add link to Material spec when available, https://github.com/flutter/flutter/issues/58769. final FlexibleSpaceBarSettings settings = context.dependOnInheritedWidgetOfExactType()!; final _ScrollUnderFlexibleConfig config = configBuilder(context); assert( @@ -2125,10 +2108,10 @@ class _ScrollUnderFlexibleSpace extends StatelessWidget { // Set maximum text scale factor to [_kMaxTitleTextScaleFactor] for the // title to keep the visual hierarchy the same even with larger font // sizes. To opt out, wrap the [title] widget in a [MediaQuery] widget - // with [MediaQueryData.textScaleFactor] set to - // `MediaQuery.textScaleFactorOf(context)`. - return MediaQuery( - data: MediaQuery.of(context).copyWith(textScaleFactor: textScaleFactor), + // with a different TextScaler. + // TODO(tahatesser): Add link to Material spec when available, https://github.com/flutter/flutter/issues/58769. + return MediaQuery.withClampedTextScaling( + maxScaleFactor: _kMaxTitleTextScaleFactor, // This column will assume the full height of the parent Stack. child: Column( children: [ diff --git a/packages/flutter/lib/src/material/bottom_navigation_bar.dart b/packages/flutter/lib/src/material/bottom_navigation_bar.dart index f85a58e8e9..15e63f6a59 100644 --- a/packages/flutter/lib/src/material/bottom_navigation_bar.dart +++ b/packages/flutter/lib/src/material/bottom_navigation_bar.dart @@ -784,11 +784,8 @@ class _Label extends StatelessWidget { if (item.label != null) { // Do not grow text in bottom navigation bar when we can show a tooltip // instead. - final MediaQueryData mediaQueryData = MediaQuery.of(context); - text = MediaQuery( - data: mediaQueryData.copyWith( - textScaleFactor: math.min(1.0, mediaQueryData.textScaleFactor), - ), + text = MediaQuery.withClampedTextScaling( + maxScaleFactor: 1.0, child: text, ); } diff --git a/packages/flutter/lib/src/material/button_style_button.dart b/packages/flutter/lib/src/material/button_style_button.dart index 9155e49ef6..c1f75e87c8 100644 --- a/packages/flutter/lib/src/material/button_style_button.dart +++ b/packages/flutter/lib/src/material/button_style_button.dart @@ -184,15 +184,12 @@ abstract class ButtonStyleButton extends StatefulWidget { EdgeInsetsGeometry geometry3x, double textScaleFactor, ) { - - if (textScaleFactor <= 1) { - return geometry1x; - } else if (textScaleFactor >= 3) { - return geometry3x; - } else if (textScaleFactor <= 2) { - return EdgeInsetsGeometry.lerp(geometry1x, geometry2x, textScaleFactor - 1)!; - } - return EdgeInsetsGeometry.lerp(geometry2x, geometry3x, textScaleFactor - 2)!; + return switch (textScaleFactor) { + <= 1 => geometry1x, + < 2 => EdgeInsetsGeometry.lerp(geometry1x, geometry2x, textScaleFactor - 1)!, + < 3 => EdgeInsetsGeometry.lerp(geometry2x, geometry3x, textScaleFactor - 2)!, + _ => geometry3x, + }; } } diff --git a/packages/flutter/lib/src/material/chip.dart b/packages/flutter/lib/src/material/chip.dart index eb457147e0..562a1878f3 100644 --- a/packages/flutter/lib/src/material/chip.dart +++ b/packages/flutter/lib/src/material/chip.dart @@ -1169,7 +1169,7 @@ class _RawChipState extends State with MaterialStateMixin, TickerProvid final EdgeInsetsGeometry defaultLabelPadding = EdgeInsets.lerp( const EdgeInsets.symmetric(horizontal: 8.0), const EdgeInsets.symmetric(horizontal: 4.0), - clampDouble(MediaQuery.textScaleFactorOf(context) - 1.0, 0.0, 1.0), + clampDouble(MediaQuery.textScalerOf(context).textScaleFactor - 1.0, 0.0, 1.0), )!; final ThemeData theme = Theme.of(context); @@ -2283,7 +2283,7 @@ class _ChipDefaultsM3 extends ChipThemeData { EdgeInsetsGeometry? get labelPadding => EdgeInsets.lerp( const EdgeInsets.symmetric(horizontal: 8.0), const EdgeInsets.symmetric(horizontal: 4.0), - clampDouble(MediaQuery.textScaleFactorOf(context) - 1.0, 0.0, 1.0), + clampDouble(MediaQuery.textScalerOf(context).textScaleFactor - 1.0, 0.0, 1.0), )!; } diff --git a/packages/flutter/lib/src/material/choice_chip.dart b/packages/flutter/lib/src/material/choice_chip.dart index 7b05db3622..8eba9b0b7d 100644 --- a/packages/flutter/lib/src/material/choice_chip.dart +++ b/packages/flutter/lib/src/material/choice_chip.dart @@ -338,7 +338,7 @@ class _ChoiceChipDefaultsM3 extends ChipThemeData { EdgeInsetsGeometry? get labelPadding => EdgeInsets.lerp( const EdgeInsets.symmetric(horizontal: 8.0), const EdgeInsets.symmetric(horizontal: 4.0), - clampDouble(MediaQuery.textScaleFactorOf(context) - 1.0, 0.0, 1.0), + clampDouble(MediaQuery.textScalerOf(context).textScaleFactor - 1.0, 0.0, 1.0), )!; } diff --git a/packages/flutter/lib/src/material/circle_avatar.dart b/packages/flutter/lib/src/material/circle_avatar.dart index 6d537775ab..3f7c9584ff 100644 --- a/packages/flutter/lib/src/material/circle_avatar.dart +++ b/packages/flutter/lib/src/material/circle_avatar.dart @@ -252,10 +252,9 @@ class CircleAvatar extends StatelessWidget { child: child == null ? null : Center( - child: MediaQuery( - // Need to ignore the ambient textScaleFactor here so that the - // text doesn't escape the avatar when the textScaleFactor is large. - data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0), + // Need to disable text scaling here so that the text doesn't + // escape the avatar when the textScaleFactor is large. + child: MediaQuery.withNoTextScaling( child: IconTheme( data: theme.iconTheme.copyWith(color: textStyle.color), child: DefaultTextStyle( diff --git a/packages/flutter/lib/src/material/date_picker.dart b/packages/flutter/lib/src/material/date_picker.dart index afb72d4b84..2fb95113d0 100644 --- a/packages/flutter/lib/src/material/date_picker.dart +++ b/packages/flutter/lib/src/material/date_picker.dart @@ -46,6 +46,7 @@ const Size _inputRangeLandscapeDialogSize = Size(496, 164.0); const Duration _dialogSizeAnimationDuration = Duration(milliseconds: 200); const double _inputFormPortraitHeight = 98.0; const double _inputFormLandscapeHeight = 108.0; +const double _kMaxTextScaleFactor = 1.3; /// Shows a dialog containing a Material Design date picker. /// @@ -436,9 +437,7 @@ class _DatePickerDialogState extends State with RestorationMix } void _handleOnDatePickerModeChange() { - if (widget.onDatePickerModeChange != null) { - widget.onDatePickerModeChange!(_entryMode.value); - } + widget.onDatePickerModeChange?.call(_entryMode.value); } void _handleEntryModeToggle() { @@ -454,7 +453,7 @@ class _DatePickerDialogState extends State with RestorationMix _handleOnDatePickerModeChange(); case DatePickerEntryMode.calendarOnly: case DatePickerEntryMode.inputOnly: - assert(false, 'Can not change entry mode from _entryMode'); + assert(false, 'Can not change entry mode from ${_entryMode.value}'); } }); } @@ -642,7 +641,7 @@ class _DatePickerDialogState extends State with RestorationMix // Constrain the textScaleFactor to the largest supported value to prevent // layout issues. - final double textScaleFactor = math.min(MediaQuery.textScaleFactorOf(context), 1.3); + final double textScaleFactor = MediaQuery.textScalerOf(context).clamp(maxScaleFactor: _kMaxTextScaleFactor).textScaleFactor; final Size dialogSize = _dialogSize(context) * textScaleFactor; final DialogTheme dialogTheme = theme.dialogTheme; return Dialog( @@ -662,10 +661,10 @@ class _DatePickerDialogState extends State with RestorationMix height: dialogSize.height, duration: _dialogSizeAnimationDuration, curve: Curves.easeIn, - child: MediaQuery( - data: MediaQuery.of(context).copyWith( - textScaleFactor: textScaleFactor, - ), + child: MediaQuery.withClampedTextScaling( + // Constrain the textScaleFactor to the largest supported value to prevent + // layout issues. + maxScaleFactor: _kMaxTextScaleFactor, child: Builder(builder: (BuildContext context) { switch (orientation) { case Orientation.portrait: @@ -1391,7 +1390,6 @@ class _DateRangePickerDialogState extends State with Rest final ThemeData theme = Theme.of(context); final bool useMaterial3 = theme.useMaterial3; final Orientation orientation = MediaQuery.orientationOf(context); - final double textScaleFactor = math.min(MediaQuery.textScaleFactorOf(context), 1.3); final MaterialLocalizations localizations = MaterialLocalizations.of(context); final DatePickerThemeData datePickerTheme = DatePickerTheme.of(context); final DatePickerThemeData defaults = DatePickerTheme.defaults(context); @@ -1535,10 +1533,8 @@ class _DateRangePickerDialogState extends State with Rest height: size.height, duration: _dialogSizeAnimationDuration, curve: Curves.easeIn, - child: MediaQuery( - data: MediaQuery.of(context).copyWith( - textScaleFactor: textScaleFactor, - ), + child: MediaQuery.withClampedTextScaling( + maxScaleFactor: _kMaxTextScaleFactor, child: Builder(builder: (BuildContext context) { return contents; }), diff --git a/packages/flutter/lib/src/material/dialog.dart b/packages/flutter/lib/src/material/dialog.dart index 181aff65f5..57300b5601 100644 --- a/packages/flutter/lib/src/material/dialog.dart +++ b/packages/flutter/lib/src/material/dialog.dart @@ -719,7 +719,7 @@ class AlertDialog extends StatelessWidget { // The paddingScaleFactor is used to adjust the padding of Dialog's // children. - final double paddingScaleFactor = _paddingScaleFactor(MediaQuery.textScaleFactorOf(context)); + final double paddingScaleFactor = _paddingScaleFactor(MediaQuery.textScalerOf(context).textScaleFactor); final TextDirection? textDirection = Directionality.maybeOf(context); Widget? iconWidget; @@ -1216,7 +1216,7 @@ class SimpleDialog extends StatelessWidget { // The paddingScaleFactor is used to adjust the padding of Dialog // children. - final double paddingScaleFactor = _paddingScaleFactor(MediaQuery.textScaleFactorOf(context)); + final double paddingScaleFactor = _paddingScaleFactor(MediaQuery.textScalerOf(context).textScaleFactor); final TextDirection? textDirection = Directionality.maybeOf(context); Widget? titleWidget; diff --git a/packages/flutter/lib/src/material/dropdown.dart b/packages/flutter/lib/src/material/dropdown.dart index a115b0982b..17bc7ec6d1 100644 --- a/packages/flutter/lib/src/material/dropdown.dart +++ b/packages/flutter/lib/src/material/dropdown.dart @@ -1355,9 +1355,8 @@ class _DropdownButtonState extends State> with WidgetsBindi // Similarly, we don't reduce the height of the button so much that its icon // would be clipped. double get _denseButtonHeight { - final double textScaleFactor = MediaQuery.textScaleFactorOf(context); final double fontSize = _textStyle!.fontSize ?? Theme.of(context).textTheme.titleMedium!.fontSize!; - final double scaledFontSize = textScaleFactor * fontSize; + final double scaledFontSize = MediaQuery.textScalerOf(context).scale(fontSize); return math.max(scaledFontSize, math.max(widget.iconSize, _kDenseButtonHeight)); } diff --git a/packages/flutter/lib/src/material/elevated_button.dart b/packages/flutter/lib/src/material/elevated_button.dart index 92d57fb5d0..5f8b4fe640 100644 --- a/packages/flutter/lib/src/material/elevated_button.dart +++ b/packages/flutter/lib/src/material/elevated_button.dart @@ -398,7 +398,7 @@ EdgeInsetsGeometry _scaledPadding(BuildContext context) { EdgeInsets.symmetric(horizontal: padding1x), EdgeInsets.symmetric(horizontal: padding1x / 2), EdgeInsets.symmetric(horizontal: padding1x / 2 / 2), - MediaQuery.textScaleFactorOf(context), + MediaQuery.textScalerOf(context).textScaleFactor, ); } @@ -506,12 +506,12 @@ class _ElevatedButtonWithIcon extends ElevatedButton { const EdgeInsetsDirectional.fromSTEB(16, 0, 24, 0), const EdgeInsetsDirectional.fromSTEB(8, 0, 12, 0), const EdgeInsetsDirectional.fromSTEB(4, 0, 6, 0), - MediaQuery.textScaleFactorOf(context), + MediaQuery.textScalerOf(context).textScaleFactor, ) : ButtonStyleButton.scaledPadding( const EdgeInsetsDirectional.fromSTEB(12, 0, 16, 0), const EdgeInsets.symmetric(horizontal: 8), const EdgeInsetsDirectional.fromSTEB(8, 0, 4, 0), - MediaQuery.textScaleFactorOf(context), + MediaQuery.textScalerOf(context).textScaleFactor, ); return super.defaultStyleOf(context).copyWith( padding: MaterialStatePropertyAll(scaledPadding), @@ -527,7 +527,7 @@ class _ElevatedButtonWithIconChild extends StatelessWidget { @override Widget build(BuildContext context) { - final double scale = MediaQuery.textScaleFactorOf(context); + final double scale = MediaQuery.textScalerOf(context).textScaleFactor; final double gap = scale <= 1 ? 8 : lerpDouble(8, 4, math.min(scale - 1, 1))!; return Row( mainAxisSize: MainAxisSize.min, diff --git a/packages/flutter/lib/src/material/filled_button.dart b/packages/flutter/lib/src/material/filled_button.dart index d0933f891b..b348e41c11 100644 --- a/packages/flutter/lib/src/material/filled_button.dart +++ b/packages/flutter/lib/src/material/filled_button.dart @@ -285,7 +285,7 @@ class FilledButton extends ButtonStyleButton { /// each state, and "others" means all other states. /// /// The `textScaleFactor` is the value of - /// `MediaQuery.textScaleFactorOf(context)` and the names of the + /// `MediaQuery.textScalerOf(context).textScaleFactor` and the names of the /// EdgeInsets constructors and `EdgeInsetsGeometry.lerp` have been /// abbreviated for readability. /// @@ -411,7 +411,7 @@ EdgeInsetsGeometry _scaledPadding(BuildContext context) { EdgeInsets.symmetric(horizontal: padding1x), EdgeInsets.symmetric(horizontal: padding1x / 2), EdgeInsets.symmetric(horizontal: padding1x / 2 / 2), - MediaQuery.textScaleFactorOf(context), + MediaQuery.textScalerOf(context).textScaleFactor, ); } @@ -514,12 +514,12 @@ class _FilledButtonWithIcon extends FilledButton { const EdgeInsetsDirectional.fromSTEB(16, 0, 24, 0), const EdgeInsetsDirectional.fromSTEB(8, 0, 12, 0), const EdgeInsetsDirectional.fromSTEB(4, 0, 6, 0), - MediaQuery.textScaleFactorOf(context), + MediaQuery.textScalerOf(context).textScaleFactor, ) : ButtonStyleButton.scaledPadding( const EdgeInsetsDirectional.fromSTEB(12, 0, 16, 0), const EdgeInsets.symmetric(horizontal: 8), const EdgeInsetsDirectional.fromSTEB(8, 0, 4, 0), - MediaQuery.textScaleFactorOf(context), + MediaQuery.textScalerOf(context).textScaleFactor, ); return super.defaultStyleOf(context).copyWith( padding: MaterialStatePropertyAll(scaledPadding), @@ -535,7 +535,7 @@ class _FilledButtonWithIconChild extends StatelessWidget { @override Widget build(BuildContext context) { - final double scale = MediaQuery.textScaleFactorOf(context); + final double scale = MediaQuery.textScalerOf(context).textScaleFactor; // Adjust the gap based on the text scale factor. Start at 8, and lerp // to 4 based on how large the text is. final double gap = scale <= 1 ? 8 : lerpDouble(8, 4, math.min(scale - 1, 1))!; diff --git a/packages/flutter/lib/src/material/filter_chip.dart b/packages/flutter/lib/src/material/filter_chip.dart index 887bb05c87..c56a1832b3 100644 --- a/packages/flutter/lib/src/material/filter_chip.dart +++ b/packages/flutter/lib/src/material/filter_chip.dart @@ -338,7 +338,7 @@ class _FilterChipDefaultsM3 extends ChipThemeData { EdgeInsetsGeometry? get labelPadding => EdgeInsets.lerp( const EdgeInsets.symmetric(horizontal: 8.0), const EdgeInsets.symmetric(horizontal: 4.0), - clampDouble(MediaQuery.textScaleFactorOf(context) - 1.0, 0.0, 1.0), + clampDouble(MediaQuery.textScalerOf(context).textScaleFactor - 1.0, 0.0, 1.0), )!; } diff --git a/packages/flutter/lib/src/material/input_chip.dart b/packages/flutter/lib/src/material/input_chip.dart index 756d557ee1..56ef93fe6c 100644 --- a/packages/flutter/lib/src/material/input_chip.dart +++ b/packages/flutter/lib/src/material/input_chip.dart @@ -321,7 +321,7 @@ class _InputChipDefaultsM3 extends ChipThemeData { EdgeInsetsGeometry? get labelPadding => EdgeInsets.lerp( const EdgeInsets.symmetric(horizontal: 8.0), const EdgeInsets.symmetric(horizontal: 4.0), - clampDouble(MediaQuery.textScaleFactorOf(context) - 1.0, 0.0, 1.0), + clampDouble(MediaQuery.textScalerOf(context).textScaleFactor - 1.0, 0.0, 1.0), )!; } diff --git a/packages/flutter/lib/src/material/input_decorator.dart b/packages/flutter/lib/src/material/input_decorator.dart index d957c7aaf2..0a9374c0bd 100644 --- a/packages/flutter/lib/src/material/input_decorator.dart +++ b/packages/flutter/lib/src/material/input_decorator.dart @@ -2406,7 +2406,7 @@ class _InputDecoratorState extends State with TickerProviderStat contentPadding = decorationContentPadding ?? EdgeInsets.zero; } else if (!border.isOutline) { // 4.0: the vertical gap between the inline elements and the floating label. - floatingLabelHeight = (4.0 + 0.75 * labelStyle.fontSize!) * MediaQuery.textScaleFactorOf(context); + floatingLabelHeight = (4.0 + 0.75 * labelStyle.fontSize!) * MediaQuery.textScalerOf(context).textScaleFactor; if (decoration.filled ?? false) { contentPadding = decorationContentPadding ?? (decorationIsDense ? const EdgeInsets.fromLTRB(12.0, 8.0, 12.0, 8.0) diff --git a/packages/flutter/lib/src/material/navigation_bar.dart b/packages/flutter/lib/src/material/navigation_bar.dart index fff6c2b435..c6c99e40d8 100644 --- a/packages/flutter/lib/src/material/navigation_bar.dart +++ b/packages/flutter/lib/src/material/navigation_bar.dart @@ -2,7 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'package:flutter/foundation.dart' show clampDouble; import 'package:flutter/widgets.dart'; import 'color_scheme.dart'; @@ -33,7 +32,7 @@ const double _kIndicatorWidth = 64; /// /// This widget does not adjust its size with the [ThemeData.visualDensity]. /// -/// The [MediaQueryData.textScaleFactor] does not adjust the size of this widget but +/// The [MediaQueryData.textScaler] does not adjust the size of this widget but /// rather the size of the [Tooltip]s displayed on long presses of the /// destinations. /// @@ -183,7 +182,7 @@ class NavigationBar extends StatelessWidget { /// automatically. /// /// The height does not adjust with [ThemeData.visualDensity] or - /// [MediaQueryData.textScaleFactor] as this component loses usability at + /// [MediaQueryData.textScaler] as this component loses usability at /// larger and smaller sizes due to the truncating of labels or smaller tap /// targets. /// @@ -383,18 +382,14 @@ class NavigationDestination extends StatelessWidget { ?? defaults.labelTextStyle!.resolve(selectedState); final TextStyle? effectiveUnselectedLabelTextStyle = navigationBarTheme.labelTextStyle?.resolve(unselectedState) ?? defaults.labelTextStyle!.resolve(unselectedState); + final TextStyle? textStyle = _isForwardOrCompleted(animation) ? effectiveSelectedLabelTextStyle : effectiveUnselectedLabelTextStyle; return Padding( padding: const EdgeInsets.only(top: 4), - child: _ClampTextScaleFactor( + child: MediaQuery.withClampedTextScaling( // Don't scale labels of destinations, instead, tooltip text will // upscale. - upperLimit: 1, - child: Text( - label, - style: _isForwardOrCompleted(animation) - ? effectiveSelectedLabelTextStyle - : effectiveUnselectedLabelTextStyle, - ), + maxScaleFactor: 1.0, + child: Text(label, style: textStyle), ), ); }, @@ -1018,53 +1013,6 @@ class _NavigationDestinationLayoutDelegate extends MultiChildLayoutDelegate { } } -/// Utility Widgets - -// Clamps [MediaQueryData.textScaleFactor] so that if it is greater than -// [upperLimit] or less than [lowerLimit], [upperLimit] or [lowerLimit] will be -// used instead for the [child] widget. -// -// Example: -// -// ```dart -// _ClampTextScaleFactor( -// upperLimit: 2.0, -// child: const Text('Foo'), // If textScaleFactor is 3.0, this will only scale 2x. -// ) -// ``` -class _ClampTextScaleFactor extends StatelessWidget { - /// Clamps the text scale factor of descendants by modifying the [MediaQuery] - /// surrounding [child]. - const _ClampTextScaleFactor({ - this.upperLimit = double.infinity, - required this.child, - }); - - /// The maximum amount that the text scale factor should be for the [child] - /// widget. - /// - /// If this is `1.5`, the textScaleFactor for child widgets will never be - /// greater than `1.5`. - final double upperLimit; - - /// The [Widget] that should have its (and its descendants) text scale factor - /// clamped. - final Widget child; - - @override - Widget build(BuildContext context) { - return MediaQuery( - data: MediaQuery.of(context).copyWith( - textScaleFactor: clampDouble(MediaQuery.textScaleFactorOf(context), - 0.0, - upperLimit, - ), - ), - child: child, - ); - } -} - /// Widget that listens to an animation, and rebuilds when the animation changes /// [AnimationStatus]. /// diff --git a/packages/flutter/lib/src/material/outlined_button.dart b/packages/flutter/lib/src/material/outlined_button.dart index 8ee11e3b3e..60ff7cbe4d 100644 --- a/packages/flutter/lib/src/material/outlined_button.dart +++ b/packages/flutter/lib/src/material/outlined_button.dart @@ -354,7 +354,7 @@ EdgeInsetsGeometry _scaledPadding(BuildContext context) { EdgeInsets.symmetric(horizontal: padding1x), EdgeInsets.symmetric(horizontal: padding1x / 2), EdgeInsets.symmetric(horizontal: padding1x / 2 / 2), - MediaQuery.textScaleFactorOf(context), + MediaQuery.textScalerOf(context).textScaleFactor, ); } @@ -439,7 +439,7 @@ class _OutlinedButtonWithIcon extends OutlinedButton { const EdgeInsetsDirectional.fromSTEB(16, 0, 24, 0), const EdgeInsetsDirectional.fromSTEB(8, 0, 12, 0), const EdgeInsetsDirectional.fromSTEB(4, 0, 6, 0), - MediaQuery.textScaleFactorOf(context), + MediaQuery.textScalerOf(context).textScaleFactor, ); return super.defaultStyleOf(context).copyWith( padding: MaterialStatePropertyAll(scaledPadding), @@ -458,7 +458,7 @@ class _OutlinedButtonWithIconChild extends StatelessWidget { @override Widget build(BuildContext context) { - final double scale = MediaQuery.textScaleFactorOf(context); + final double scale = MediaQuery.textScalerOf(context).textScaleFactor; final double gap = scale <= 1 ? 8 : lerpDouble(8, 4, math.min(scale - 1, 1))!; return Row( mainAxisSize: MainAxisSize.min, diff --git a/packages/flutter/lib/src/material/selectable_text.dart b/packages/flutter/lib/src/material/selectable_text.dart index 433de56181..8616a4f8ba 100644 --- a/packages/flutter/lib/src/material/selectable_text.dart +++ b/packages/flutter/lib/src/material/selectable_text.dart @@ -185,7 +185,13 @@ class SelectableText extends StatefulWidget { this.strutStyle, this.textAlign, this.textDirection, + @Deprecated( + 'Use textScaler instead. ' + 'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. ' + 'This feature was deprecated after v3.12.0-2.0.pre.', + ) this.textScaleFactor, + this.textScaler, this.showCursor = false, this.autofocus = false, @Deprecated( @@ -218,6 +224,10 @@ class SelectableText extends StatefulWidget { (maxLines == null) || (minLines == null) || (maxLines >= minLines), "minLines can't be greater than maxLines", ), + assert( + textScaler == null || textScaleFactor == null, + 'textScaleFactor is deprecated and cannot be specified when textScaler is specified.', + ), textSpan = null; /// Creates a selectable text widget with a [TextSpan]. @@ -234,7 +244,13 @@ class SelectableText extends StatefulWidget { this.strutStyle, this.textAlign, this.textDirection, + @Deprecated( + 'Use textScaler instead. ' + 'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. ' + 'This feature was deprecated after v3.12.0-2.0.pre.', + ) this.textScaleFactor, + this.textScaler, this.showCursor = false, this.autofocus = false, @Deprecated( @@ -267,6 +283,10 @@ class SelectableText extends StatefulWidget { (maxLines == null) || (minLines == null) || (maxLines >= minLines), "minLines can't be greater than maxLines", ), + assert( + textScaler == null || textScaleFactor == null, + 'textScaleFactor is deprecated and cannot be specified when textScaler is specified.', + ), data = null; /// The text to display. @@ -322,8 +342,16 @@ class SelectableText extends StatefulWidget { final TextDirection? textDirection; /// {@macro flutter.widgets.editableText.textScaleFactor} + @Deprecated( + 'Use textScaler instead. ' + 'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. ' + 'This feature was deprecated after v3.12.0-2.0.pre.', + ) final double? textScaleFactor; + /// {@macro flutter.painting.textPainter.textScaler} + final TextScaler? textScaler; + /// {@macro flutter.widgets.editableText.autofocus} final bool autofocus; @@ -457,6 +485,7 @@ class SelectableText extends StatefulWidget { properties.add(EnumProperty('textAlign', textAlign, defaultValue: null)); properties.add(EnumProperty('textDirection', textDirection, defaultValue: null)); properties.add(DoubleProperty('textScaleFactor', textScaleFactor, defaultValue: null)); + properties.add(DiagnosticsProperty('textScaler', textScaler, defaultValue: null)); properties.add(DoubleProperty('cursorWidth', cursorWidth, defaultValue: 2.0)); properties.add(DoubleProperty('cursorHeight', cursorHeight, defaultValue: null)); properties.add(DiagnosticsProperty('cursorRadius', cursorRadius, defaultValue: null)); @@ -671,6 +700,10 @@ class _SelectableTextState extends State implements TextSelectio if (effectiveTextStyle == null || effectiveTextStyle.inherit) { effectiveTextStyle = defaultTextStyle.style.merge(widget.style ?? _controller._textSpan.style); } + final TextScaler? effectiveScaler = widget.textScaler ?? switch (widget.textScaleFactor) { + null => null, + final double textScaleFactor => TextScaler.linear(textScaleFactor), + }; final Widget child = RepaintBoundary( child: EditableText( key: editableTextKey, @@ -686,7 +719,7 @@ class _SelectableTextState extends State implements TextSelectio strutStyle: widget.strutStyle ?? const StrutStyle(), textAlign: widget.textAlign ?? defaultTextStyle.textAlign ?? TextAlign.start, textDirection: widget.textDirection, - textScaleFactor: widget.textScaleFactor, + textScaler: effectiveScaler, autofocus: widget.autofocus, forceLine: false, minLines: widget.minLines, diff --git a/packages/flutter/lib/src/material/slider.dart b/packages/flutter/lib/src/material/slider.dart index 6680aaa144..61acbf04ee 100644 --- a/packages/flutter/lib/src/material/slider.dart +++ b/packages/flutter/lib/src/material/slider.dart @@ -889,8 +889,8 @@ class _SliderState extends State with TickerProviderStateMixin { // This needs to be updated when accessibility // guidelines are available on the material specs page // https://m3.material.io/components/sliders/accessibility. - ? math.min(MediaQuery.textScaleFactorOf(context), 1.3) - : MediaQuery.textScaleFactorOf(context); + ? MediaQuery.textScalerOf(context).clamp(maxScaleFactor: 1.3).textScaleFactor + : MediaQuery.textScalerOf(context).textScaleFactor; return Semantics( container: true, diff --git a/packages/flutter/lib/src/material/text_button.dart b/packages/flutter/lib/src/material/text_button.dart index 8e5c2db548..223c7f3b03 100644 --- a/packages/flutter/lib/src/material/text_button.dart +++ b/packages/flutter/lib/src/material/text_button.dart @@ -248,7 +248,7 @@ class TextButton extends ButtonStyleButton { /// each state and "others" means all other states. /// /// The `textScaleFactor` is the value of - /// `MediaQuery.textScaleFactorOf(context)` and the names of the + /// `MediaQuery.textScalerOf(context).textScaleFactor` and the names of the /// EdgeInsets constructors and `EdgeInsetsGeometry.lerp` have been /// abbreviated for readability. /// @@ -385,7 +385,7 @@ EdgeInsetsGeometry _scaledPadding(BuildContext context) { useMaterial3 ? const EdgeInsets.symmetric(horizontal: 12, vertical: 8) : const EdgeInsets.all(8), const EdgeInsets.symmetric(horizontal: 8), const EdgeInsets.symmetric(horizontal: 4), - MediaQuery.textScaleFactorOf(context), + MediaQuery.textScalerOf(context).textScaleFactor, ); } @@ -500,7 +500,7 @@ class _TextButtonWithIcon extends TextButton { useMaterial3 ? const EdgeInsetsDirectional.fromSTEB(12, 8, 16, 8) : const EdgeInsets.all(8), const EdgeInsets.symmetric(horizontal: 4), const EdgeInsets.symmetric(horizontal: 4), - MediaQuery.textScaleFactorOf(context), + MediaQuery.textScalerOf(context).textScaleFactor, ); return super.defaultStyleOf(context).copyWith( padding: MaterialStatePropertyAll(scaledPadding), @@ -519,7 +519,7 @@ class _TextButtonWithIconChild extends StatelessWidget { @override Widget build(BuildContext context) { - final double scale = MediaQuery.textScaleFactorOf(context); + final double scale = MediaQuery.textScalerOf(context).textScaleFactor; final double gap = scale <= 1 ? 8 : lerpDouble(8, 4, math.min(scale - 1, 1))!; return Row( mainAxisSize: MainAxisSize.min, diff --git a/packages/flutter/lib/src/material/time_picker.dart b/packages/flutter/lib/src/material/time_picker.dart index 479438aa15..1d2e9dc2a9 100644 --- a/packages/flutter/lib/src/material/time_picker.dart +++ b/packages/flutter/lib/src/material/time_picker.dart @@ -348,7 +348,7 @@ class _HourMinuteControl extends StatelessWidget { child: Text( text, style: effectiveStyle, - textScaleFactor: 1, + textScaler: TextScaler.noScaling, ), ), ), @@ -479,7 +479,7 @@ class _StringFragment extends StatelessWidget { child: Text( _stringFragmentValue(timeOfDayFormat), style: effectiveStyle, - textScaleFactor: 1, + textScaler: TextScaler.noScaling, textAlign: TextAlign.center, ), ), @@ -696,7 +696,7 @@ class _AmPmButton extends StatelessWidget { final Color resolvedBackgroundColor = MaterialStateProperty.resolveAs(timePickerTheme.dayPeriodColor ?? defaultTheme.dayPeriodColor, states); final Color resolvedTextColor = MaterialStateProperty.resolveAs(timePickerTheme.dayPeriodTextColor ?? defaultTheme.dayPeriodTextColor, states); final TextStyle? resolvedTextStyle = MaterialStateProperty.resolveAs(timePickerTheme.dayPeriodTextStyle ?? defaultTheme.dayPeriodTextStyle, states)?.copyWith(color: resolvedTextColor); - final double buttonTextScaleFactor = math.min(MediaQuery.textScaleFactorOf(context), 2); + final TextScaler buttonTextScaler = MediaQuery.textScalerOf(context).clamp(maxScaleFactor: 2.0); return Material( color: resolvedBackgroundColor, @@ -710,7 +710,7 @@ class _AmPmButton extends StatelessWidget { child: Text( label, style: resolvedTextStyle, - textScaleFactor: buttonTextScaleFactor, + textScaler: buttonTextScaler, ), ), ), @@ -1394,14 +1394,13 @@ class _DialState extends State<_Dial> with SingleTickerProviderStateMixin { required String label, required VoidCallback onTap, }) { - final double labelScaleFactor = math.min(MediaQuery.textScaleFactorOf(context), 2); return _TappableLabel( value: value, inner: inner, painter: TextPainter( text: TextSpan(style: textStyle, text: label), textDirection: TextDirection.ltr, - textScaleFactor: labelScaleFactor, + textScaler: MediaQuery.textScalerOf(context).clamp(maxScaleFactor: 2.0), )..layout(), onTap: onTap, ); @@ -2063,8 +2062,7 @@ class _HourMinuteTextFieldState extends State<_HourMinuteTextField> with Restora return SizedBox.fromSize( size: alwaysUse24HourFormat ? defaultTheme.hourMinuteInputSize24Hour : defaultTheme.hourMinuteInputSize, - child: MediaQuery( - data: MediaQuery.of(context).copyWith(textScaleFactor: 1), + child: MediaQuery.withNoTextScaling( child: UnmanagedRestorationScope( bucket: bucket, child: Semantics( @@ -2311,7 +2309,7 @@ class _TimePickerDialogState extends State with RestorationMix // Constrain the textScaleFactor to prevent layout issues. Since only some // parts of the time picker scale up with textScaleFactor, we cap the factor // to 1.1 as that provides enough space to reasonably fit all the content. - final double textScaleFactor = math.min(MediaQuery.textScaleFactorOf(context), 1.1); + final double textScaleFactor = MediaQuery.textScalerOf(context).clamp(maxScaleFactor: 1.1).textScaleFactor; final Size timePickerSize; switch (_entryMode.value) { diff --git a/packages/flutter/lib/src/painting/inline_span.dart b/packages/flutter/lib/src/painting/inline_span.dart index 9037b99c09..175ee7d896 100644 --- a/packages/flutter/lib/src/painting/inline_span.dart +++ b/packages/flutter/lib/src/painting/inline_span.dart @@ -9,6 +9,7 @@ import 'package:flutter/gestures.dart'; import 'basic_types.dart'; import 'text_painter.dart'; +import 'text_scaler.dart'; import 'text_span.dart'; import 'text_style.dart'; @@ -209,7 +210,7 @@ abstract class InlineSpan extends DiagnosticableTree { /// Apply the properties of this object to the given [ParagraphBuilder], from /// which a [Paragraph] can be obtained. /// - /// The `textScaleFactor` parameter specifies a scale that the text and + /// The `textScaler` parameter specifies a [TextScaler] that the text and /// placeholders will be scaled by. The scaling is performed before layout, /// so the text will be laid out with the scaled glyphs and placeholders. /// @@ -218,7 +219,10 @@ abstract class InlineSpan extends DiagnosticableTree { /// in the same order as defined in the [InlineSpan] tree. /// /// [Paragraph] objects can be drawn on [Canvas] objects. - void build(ui.ParagraphBuilder builder, { double textScaleFactor = 1.0, List? dimensions }); + void build(ui.ParagraphBuilder builder, { + TextScaler textScaler = TextScaler.noScaling, + List? dimensions, + }); /// Walks this [InlineSpan] and any descendants in pre-order and calls `visitor` /// for each span that has content. diff --git a/packages/flutter/lib/src/painting/text_painter.dart b/packages/flutter/lib/src/painting/text_painter.dart index bcad34b23d..07a26d79e3 100644 --- a/packages/flutter/lib/src/painting/text_painter.dart +++ b/packages/flutter/lib/src/painting/text_painter.dart @@ -22,6 +22,7 @@ import 'basic_types.dart'; import 'inline_span.dart'; import 'placeholder_span.dart'; import 'strut_style.dart'; +import 'text_scaler.dart'; import 'text_span.dart'; export 'package:flutter/services.dart' show TextRange, TextSelection; @@ -487,7 +488,13 @@ class TextPainter { InlineSpan? text, TextAlign textAlign = TextAlign.start, TextDirection? textDirection, + @Deprecated( + 'Use textScaler instead. ' + 'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. ' + 'This feature was deprecated after v3.12.0-2.0.pre.', + ) double textScaleFactor = 1.0, + TextScaler textScaler = TextScaler.noScaling, int? maxLines, String? ellipsis, Locale? locale, @@ -496,10 +503,11 @@ class TextPainter { ui.TextHeightBehavior? textHeightBehavior, }) : assert(text == null || text.debugAssertIsValid()), assert(maxLines == null || maxLines > 0), + assert(textScaleFactor == 1.0 || identical(textScaler, TextScaler.noScaling), 'Use textScaler instead.'), _text = text, _textAlign = textAlign, _textDirection = textDirection, - _textScaleFactor = textScaleFactor, + _textScaler = textScaler == TextScaler.noScaling ? TextScaler.linear(textScaleFactor) : textScaler, _maxLines = maxLines, _ellipsis = ellipsis, _locale = locale, @@ -519,7 +527,13 @@ class TextPainter { required InlineSpan text, required TextDirection textDirection, TextAlign textAlign = TextAlign.start, + @Deprecated( + 'Use textScaler instead. ' + 'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. ' + 'This feature was deprecated after v3.12.0-2.0.pre.', + ) double textScaleFactor = 1.0, + TextScaler textScaler = TextScaler.noScaling, int? maxLines, String? ellipsis, Locale? locale, @@ -529,11 +543,15 @@ class TextPainter { double minWidth = 0.0, double maxWidth = double.infinity, }) { + assert( + textScaleFactor == 1.0 || identical(textScaler, TextScaler.noScaling), + 'Use textScaler instead.', + ); final TextPainter painter = TextPainter( text: text, textAlign: textAlign, textDirection: textDirection, - textScaleFactor: textScaleFactor, + textScaler: textScaler == TextScaler.noScaling ? TextScaler.linear(textScaleFactor) : textScaler, maxLines: maxLines, ellipsis: ellipsis, locale: locale, @@ -561,7 +579,13 @@ class TextPainter { required InlineSpan text, required TextDirection textDirection, TextAlign textAlign = TextAlign.start, + @Deprecated( + 'Use textScaler instead. ' + 'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. ' + 'This feature was deprecated after v3.12.0-2.0.pre.', + ) double textScaleFactor = 1.0, + TextScaler textScaler = TextScaler.noScaling, int? maxLines, String? ellipsis, Locale? locale, @@ -571,11 +595,15 @@ class TextPainter { double minWidth = 0.0, double maxWidth = double.infinity, }) { + assert( + textScaleFactor == 1.0 || identical(textScaler, TextScaler.noScaling), + 'Use textScaler instead.', + ); final TextPainter painter = TextPainter( text: text, textAlign: textAlign, textDirection: textDirection, - textScaleFactor: textScaleFactor, + textScaler: textScaler == TextScaler.noScaling ? TextScaler.linear(textScaleFactor) : textScaler, maxLines: maxLines, ellipsis: ellipsis, locale: locale, @@ -728,19 +756,48 @@ class TextPainter { _layoutTemplate = null; // Shouldn't really matter, but for strict correctness... } + /// Deprecated. Will be removed in a future version of Flutter. Use + /// [textScaler] instead. + /// /// The number of font pixels for each logical pixel. /// /// For example, if the text scale factor is 1.5, text will be 50% larger than /// the specified font size. /// /// After this is set, you must call [layout] before the next call to [paint]. - double get textScaleFactor => _textScaleFactor; - double _textScaleFactor; + @Deprecated( + 'Use textScaler instead. ' + 'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. ' + 'This feature was deprecated after v3.12.0-2.0.pre.', + ) + double get textScaleFactor => textScaler.textScaleFactor; + @Deprecated( + 'Use textScaler instead. ' + 'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. ' + 'This feature was deprecated after v3.12.0-2.0.pre.', + ) set textScaleFactor(double value) { - if (_textScaleFactor == value) { + textScaler = TextScaler.linear(value); + } + + /// {@template flutter.painting.textPainter.textScaler} + /// The font scaling strategy to use when laying out and rendering the text. + /// + /// The value usually comes from [MediaQuery.textScalerOf], which typically + /// reflects the user-specified text scaling value in the platform's + /// accessibility settings. The [TextStyle.fontSize] of the text will be + /// adjusted by the [TextScaler] before the text is laid out and rendered. + /// {@endtemplate} + /// + /// The [layout] method must be called after [textScaler] changes as it + /// affects the text layout. + TextScaler get textScaler => _textScaler; + TextScaler _textScaler; + set textScaler(TextScaler value) { + if (value == _textScaler) { return; } - _textScaleFactor = value; + _textScaler = value; markNeedsLayout(); _layoutTemplate?.dispose(); _layoutTemplate = null; @@ -905,7 +962,7 @@ class TextPainter { return _text!.style?.getParagraphStyle( textAlign: textAlign, textDirection: textDirection ?? defaultTextDirection, - textScaleFactor: textScaleFactor, + textScaler: textScaler, maxLines: _maxLines, textHeightBehavior: _textHeightBehavior, ellipsis: _ellipsis, @@ -916,8 +973,8 @@ class TextPainter { textDirection: textDirection ?? defaultTextDirection, // Use the default font size to multiply by as RichText does not // perform inheriting [TextStyle]s and would otherwise - // fail to apply textScaleFactor. - fontSize: _kDefaultFontSize * textScaleFactor, + // fail to apply textScaler. + fontSize: textScaler.scale(_kDefaultFontSize), maxLines: maxLines, textHeightBehavior: _textHeightBehavior, ellipsis: ellipsis, @@ -930,7 +987,7 @@ class TextPainter { final ui.ParagraphBuilder builder = ui.ParagraphBuilder( _createParagraphStyle(TextDirection.rtl), ); // direction doesn't matter, text is just a space - final ui.TextStyle? textStyle = text?.style?.getTextStyle(textScaleFactor: textScaleFactor); + final ui.TextStyle? textStyle = text?.style?.getTextStyle(textScaler: textScaler); if (textStyle != null) { builder.pushStyle(textStyle); } @@ -1025,7 +1082,7 @@ class TextPainter { // assign it to _paragraph. ui.Paragraph _createParagraph(InlineSpan text) { final ui.ParagraphBuilder builder = ui.ParagraphBuilder(_createParagraphStyle()); - text.build(builder, textScaleFactor: textScaleFactor, dimensions: _placeholderDimensions); + text.build(builder, textScaler: textScaler, dimensions: _placeholderDimensions); assert(() { _debugMarkNeedsLayoutCallStack = null; return true; diff --git a/packages/flutter/lib/src/painting/text_scaler.dart b/packages/flutter/lib/src/painting/text_scaler.dart new file mode 100644 index 0000000000..554cfb892f --- /dev/null +++ b/packages/flutter/lib/src/painting/text_scaler.dart @@ -0,0 +1,151 @@ +// 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 'dart:math' show max, min; + +import 'package:flutter/foundation.dart'; + +/// A class that describes how textual contents should be scaled for better +/// readability. +/// +/// The [scale] function computes the scaled font size given the original +/// unscaled font size specified by app developers. +/// +/// The [==] operator defines the equality of 2 [TextScaler]s, which the +/// framework uses to determine whether text widgets should rebuild when their +/// [TextScaler] changes. Consider overridding the [==] operator if applicable +/// to avoid unnecessary rebuilds. +@immutable +abstract class TextScaler { + /// Creates a TextScaler. + const TextScaler(); + + /// Creates a proportional [TextScaler] that scales the incoming font size by + /// multiplying it with the given `textScaleFactor`. + const factory TextScaler.linear(double textScaleFactor) = _LinearTextScaler; + + /// A [TextScaler] that doesn't scale the input font size. + /// + /// This is equivalent to `TextScaler.linear(1.0)`, the [TextScaler.scale] + /// implementation always returns the input font size as-is. + static const TextScaler noScaling = _LinearTextScaler(1.0); + + /// Computes the scaled font size (in logical pixels) with the given unscaled + /// `fontSize` (in logical pixels). + /// + /// The input `fontSize` must be finite and non-negative. + /// + /// When given the same `fontSize` input, this method returns the same value. + /// The output of a larger input `fontSize` is typically larger than that of a + /// smaller input, but on unusual occasions they may produce the same output. + /// For example, some platforms use single-precision floats to represent font + /// sizes, as a result of truncation two different unscaled font sizes can be + /// scaled to the same value. + double scale(double fontSize); + + /// The estimated number of font pixels for each logical pixel. This property + /// exists only for backward compatibility purposes, and will be removed in + /// a future version of Flutter. + /// + /// The value of this property is only an estimate, so it may not reflect the + /// exact text scaling strategy this [TextScaler] represents, especially when + /// this [TextScaler] is not linear. Consider using [TextScaler.scale] instead. + @Deprecated( + 'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. ' + 'This feature was deprecated after v3.12.0-2.0.pre.', + ) + double get textScaleFactor; + + /// Returns a new [TextScaler] that restricts the scaled font size to within + /// the range `[minScaleFactor * fontSize, maxScaleFactor * fontSize]`. + TextScaler clamp({ double minScaleFactor = 0, double maxScaleFactor = double.infinity }) { + assert(maxScaleFactor >= minScaleFactor); + assert(!maxScaleFactor.isNaN); + assert(minScaleFactor.isFinite); + assert(minScaleFactor >= 0); + + return minScaleFactor == maxScaleFactor + ? TextScaler.linear(minScaleFactor) + : _ClampedTextScaler(this, minScaleFactor, maxScaleFactor); + } +} + +final class _LinearTextScaler implements TextScaler { + const _LinearTextScaler(this.textScaleFactor) : assert(textScaleFactor >= 0); + + @override + final double textScaleFactor; + + @override + double scale(double fontSize) { + assert(fontSize >= 0); + assert(fontSize.isFinite); + return fontSize * textScaleFactor; + } + + @override + TextScaler clamp({ double minScaleFactor = 0, double maxScaleFactor = double.infinity }) { + assert(maxScaleFactor >= minScaleFactor); + assert(!maxScaleFactor.isNaN); + assert(minScaleFactor.isFinite); + assert(minScaleFactor >= 0); + + final double newScaleFactor = clampDouble(textScaleFactor, minScaleFactor, maxScaleFactor); + return newScaleFactor == textScaleFactor ? this : _LinearTextScaler(newScaleFactor); + } + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + return other is _LinearTextScaler && other.textScaleFactor == textScaleFactor; + } + + @override + int get hashCode => textScaleFactor.hashCode; + + @override + String toString() => textScaleFactor == 1.0 ? 'no scaling' : 'linear (${textScaleFactor}x)'; +} + +final class _ClampedTextScaler implements TextScaler { + const _ClampedTextScaler(this.scaler, this.minScale, this.maxScale) : assert(maxScale > minScale); + final TextScaler scaler; + final double minScale; + final double maxScale; + + @override + double get textScaleFactor => clampDouble(scaler.textScaleFactor, minScale, maxScale); + + @override + double scale(double fontSize) { + assert(fontSize >= 0); + assert(fontSize.isFinite); + return minScale == maxScale + ? minScale * fontSize + : clampDouble(scaler.scale(fontSize), minScale * fontSize, maxScale * fontSize); + } + + @override + TextScaler clamp({ double minScaleFactor = 0, double maxScaleFactor = double.infinity }) { + return minScaleFactor == maxScaleFactor + ? _LinearTextScaler(minScaleFactor) + : _ClampedTextScaler(scaler, max(minScaleFactor, minScale), min(maxScaleFactor, maxScale)); + } + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + return other is _ClampedTextScaler + && minScale == other.minScale + && maxScale == other.maxScale + && (minScale == maxScale || scaler == other.scaler); + } + + @override + int get hashCode => minScale == maxScale ? minScale.hashCode : Object.hash(scaler, minScale, maxScale); +} diff --git a/packages/flutter/lib/src/painting/text_span.dart b/packages/flutter/lib/src/painting/text_span.dart index 34168be205..c3f3731033 100644 --- a/packages/flutter/lib/src/painting/text_span.dart +++ b/packages/flutter/lib/src/painting/text_span.dart @@ -11,6 +11,7 @@ import 'package:flutter/services.dart'; import 'basic_types.dart'; import 'inline_span.dart'; import 'text_painter.dart'; +import 'text_scaler.dart'; // Examples can assume: // late TextSpan myTextSpan; @@ -267,13 +268,13 @@ class TextSpan extends InlineSpan implements HitTestTarget, MouseTrackerAnnotati @override void build( ui.ParagraphBuilder builder, { - double textScaleFactor = 1.0, + TextScaler textScaler = TextScaler.noScaling, List? dimensions, }) { assert(debugAssertIsValid()); final bool hasStyle = style != null; if (hasStyle) { - builder.pushStyle(style!.getTextStyle(textScaleFactor: textScaleFactor)); + builder.pushStyle(style!.getTextStyle(textScaler: textScaler)); } if (text != null) { try { @@ -294,7 +295,7 @@ class TextSpan extends InlineSpan implements HitTestTarget, MouseTrackerAnnotati for (final InlineSpan child in children) { child.build( builder, - textScaleFactor: textScaleFactor, + textScaler: textScaler, dimensions: dimensions, ); } diff --git a/packages/flutter/lib/src/painting/text_style.dart b/packages/flutter/lib/src/painting/text_style.dart index b00e0191d0..d88e5a0262 100644 --- a/packages/flutter/lib/src/painting/text_style.dart +++ b/packages/flutter/lib/src/painting/text_style.dart @@ -19,6 +19,7 @@ import 'basic_types.dart'; import 'colors.dart'; import 'strut_style.dart'; import 'text_painter.dart'; +import 'text_scaler.dart'; const String _kDefaultDebugLabel = 'unknown'; @@ -1271,7 +1272,24 @@ class TextStyle with Diagnosticable { } /// The style information for text runs, encoded for use by `dart:ui`. - ui.TextStyle getTextStyle({ double textScaleFactor = 1.0 }) { + ui.TextStyle getTextStyle({ + @Deprecated( + 'Use textScaler instead. ' + 'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. ' + 'This feature was deprecated after v3.12.0-2.0.pre.', + ) + double textScaleFactor = 1.0, + TextScaler textScaler = TextScaler.noScaling, + }) { + assert( + identical(textScaler, TextScaler.noScaling) || textScaleFactor == 1.0, + 'textScaleFactor is deprecated and cannot be specified when textScaler is specified.', + ); + final double? fontSize = switch (this.fontSize) { + null => null, + final double size when textScaler == TextScaler.noScaling => size * textScaleFactor, + final double size => textScaler.scale(size), + }; return ui.TextStyle( color: color, decoration: decoration, @@ -1284,16 +1302,17 @@ class TextStyle with Diagnosticable { leadingDistribution: leadingDistribution, fontFamily: fontFamily, fontFamilyFallback: fontFamilyFallback, - fontSize: fontSize == null ? null : fontSize! * textScaleFactor, + fontSize: fontSize, letterSpacing: letterSpacing, wordSpacing: wordSpacing, height: height, locale: locale, foreground: foreground, - background: background ?? (backgroundColor != null - ? (Paint()..color = backgroundColor!) - : null - ), + background: switch ((background, backgroundColor)) { + (final Paint paint, _) => paint, + (_, final Color color) => Paint()..color = color, + _ => null, + }, shadows: shadows, fontFeatures: fontFeatures, fontVariations: fontVariations, @@ -1311,7 +1330,7 @@ class TextStyle with Diagnosticable { ui.ParagraphStyle getParagraphStyle({ TextAlign? textAlign, TextDirection? textDirection, - double textScaleFactor = 1.0, + TextScaler textScaler = TextScaler.noScaling, String? ellipsis, int? maxLines, ui.TextHeightBehavior? textHeightBehavior, @@ -1327,6 +1346,7 @@ class TextStyle with Diagnosticable { final ui.TextLeadingDistribution? leadingDistribution = this.leadingDistribution; final ui.TextHeightBehavior? effectiveTextHeightBehavior = textHeightBehavior ?? (leadingDistribution == null ? null : ui.TextHeightBehavior(leadingDistribution: leadingDistribution)); + return ui.ParagraphStyle( textAlign: textAlign, textDirection: textDirection, @@ -1335,13 +1355,16 @@ class TextStyle with Diagnosticable { fontWeight: fontWeight ?? this.fontWeight, fontStyle: fontStyle ?? this.fontStyle, fontFamily: fontFamily ?? this.fontFamily, - fontSize: (fontSize ?? this.fontSize ?? _kDefaultFontSize) * textScaleFactor, + fontSize: textScaler.scale(fontSize ?? this.fontSize ?? _kDefaultFontSize), height: height ?? this.height, textHeightBehavior: effectiveTextHeightBehavior, strutStyle: strutStyle == null ? null : ui.StrutStyle( fontFamily: strutStyle.fontFamily, fontFamilyFallback: strutStyle.fontFamilyFallback, - fontSize: strutStyle.fontSize == null ? null : strutStyle.fontSize! * textScaleFactor, + fontSize: switch (strutStyle.fontSize) { + null => null, + final double unscaled => textScaler.scale(unscaled), + }, height: strutStyle.height, leading: strutStyle.leading, fontWeight: strutStyle.fontWeight, diff --git a/packages/flutter/lib/src/rendering/editable.dart b/packages/flutter/lib/src/rendering/editable.dart index a357bde585..d03d5f6b2d 100644 --- a/packages/flutter/lib/src/rendering/editable.dart +++ b/packages/flutter/lib/src/rendering/editable.dart @@ -288,7 +288,13 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, bool expands = false, StrutStyle? strutStyle, Color? selectionColor, + @Deprecated( + 'Use textScaler instead. ' + 'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. ' + 'This feature was deprecated after v3.12.0-2.0.pre.', + ) double textScaleFactor = 1.0, + TextScaler textScaler = TextScaler.noScaling, TextSelection? selection, required ViewportOffset offset, this.ignorePointer = false, @@ -326,6 +332,10 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, !expands || (maxLines == null && minLines == null), 'minLines and maxLines must be null when expands is true.', ), + assert( + identical(textScaler, TextScaler.noScaling) || textScaleFactor == 1.0, + 'textScaleFactor is deprecated and cannot be specified when textScaler is specified.', + ), assert(obscuringCharacter.characters.length == 1), assert(cursorWidth >= 0.0), assert(cursorHeight == null || cursorHeight >= 0.0), @@ -333,7 +343,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, text: text, textAlign: textAlign, textDirection: textDirection, - textScaleFactor: textScaleFactor, + textScaler: textScaler == TextScaler.noScaling ? TextScaler.linear(textScaleFactor) : textScaler, locale: locale, maxLines: maxLines == 1 ? 1 : null, strutStyle: strutStyle, @@ -985,16 +995,35 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, _selectionPainter.highlightColor = value; } + /// Deprecated. Will be removed in a future version of Flutter. Use + /// [textScaler] instead. + /// /// The number of font pixels for each logical pixel. /// /// For example, if the text scale factor is 1.5, text will be 50% larger than /// the specified font size. + @Deprecated( + 'Use textScaler instead. ' + 'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. ' + 'This feature was deprecated after v3.12.0-2.0.pre.', + ) double get textScaleFactor => _textPainter.textScaleFactor; + @Deprecated( + 'Use textScaler instead. ' + 'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. ' + 'This feature was deprecated after v3.12.0-2.0.pre.', + ) set textScaleFactor(double value) { - if (_textPainter.textScaleFactor == value) { + textScaler = TextScaler.linear(value); + } + + /// {@macro flutter.painting.textPainter.textScaler} + TextScaler get textScaler => _textPainter.textScaler; + set textScaler(TextScaler value) { + if (_textPainter.textScaler == value) { return; } - _textPainter.textScaleFactor = value; + _textPainter.textScaler = value; markNeedsTextLayout(); } @@ -2528,7 +2557,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, properties.add(IntProperty('minLines', minLines)); properties.add(DiagnosticsProperty('expands', expands, defaultValue: false)); properties.add(ColorProperty('selectionColor', selectionColor)); - properties.add(DoubleProperty('textScaleFactor', textScaleFactor)); + properties.add(DiagnosticsProperty('textScaler', textScaler, defaultValue: TextScaler.noScaling)); properties.add(DiagnosticsProperty('locale', locale, defaultValue: null)); properties.add(DiagnosticsProperty('selection', selection)); properties.add(DiagnosticsProperty('offset', offset)); diff --git a/packages/flutter/lib/src/rendering/paragraph.dart b/packages/flutter/lib/src/rendering/paragraph.dart index 066f6137e7..4fd946a88d 100644 --- a/packages/flutter/lib/src/rendering/paragraph.dart +++ b/packages/flutter/lib/src/rendering/paragraph.dart @@ -253,7 +253,7 @@ class RenderParagraph extends RenderBox with ContainerRenderObjectMixin 0), + assert( + identical(textScaler, TextScaler.noScaling) || textScaleFactor == 1.0, + 'textScaleFactor is deprecated and cannot be specified when textScaler is specified.', + ), _softWrap = softWrap, _overflow = overflow, _selectionColor = selectionColor, @@ -280,7 +290,7 @@ class RenderParagraph extends RenderBox with ContainerRenderObjectMixin _textPainter.textScaleFactor; + @Deprecated( + 'Use textScaler instead. ' + 'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. ' + 'This feature was deprecated after v3.12.0-2.0.pre.', + ) set textScaleFactor(double value) { - if (_textPainter.textScaleFactor == value) { + textScaler = TextScaler.linear(value); + } + + /// {@macro flutter.painting.textPainter.textScaler} + TextScaler get textScaler => _textPainter.textScaler; + set textScaler(TextScaler value) { + if (_textPainter.textScaler == value) { return; } - _textPainter.textScaleFactor = value; + _textPainter.textScaler = value; _overflowShader = null; markNeedsLayout(); } @@ -791,7 +820,7 @@ class RenderParagraph extends RenderBox with ContainerRenderObjectMixin('overflow', overflow)); properties.add( - DoubleProperty( - 'textScaleFactor', - textScaleFactor, - defaultValue: 1.0, - ), + DiagnosticsProperty('textScaler', textScaler, defaultValue: TextScaler.noScaling), ); properties.add( DiagnosticsProperty( diff --git a/packages/flutter/lib/src/widgets/basic.dart b/packages/flutter/lib/src/widgets/basic.dart index 100f68d584..3dc2786736 100644 --- a/packages/flutter/lib/src/widgets/basic.dart +++ b/packages/flutter/lib/src/widgets/basic.dart @@ -5715,7 +5715,7 @@ class Flow extends MultiChildRenderObjectWidget { class RichText extends MultiChildRenderObjectWidget { /// Creates a paragraph of rich text. /// - /// The [text], [textAlign], [softWrap], [overflow], and [textScaleFactor] + /// The [text], [textAlign], [softWrap], [overflow], and [textScaler] /// arguments must not be null. /// /// The [maxLines] property may be null (and indeed defaults to null), but if @@ -5730,7 +5730,13 @@ class RichText extends MultiChildRenderObjectWidget { this.textDirection, this.softWrap = true, this.overflow = TextOverflow.clip, - this.textScaleFactor = 1.0, + @Deprecated( + 'Use textScaler instead. ' + 'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. ' + 'This feature was deprecated after v3.12.0-2.0.pre.', + ) + double textScaleFactor = 1.0, + TextScaler textScaler = TextScaler.noScaling, this.maxLines, this.locale, this.strutStyle, @@ -5740,7 +5746,17 @@ class RichText extends MultiChildRenderObjectWidget { this.selectionColor, }) : assert(maxLines == null || maxLines > 0), assert(selectionRegistrar == null || selectionColor != null), - super(children: WidgetSpan.extractFromInlineSpan(text, textScaleFactor)); + assert(textScaleFactor == 1.0 || identical(textScaler, TextScaler.noScaling), 'Use textScaler instead.'), + textScaler = _effectiveTextScalerFrom(textScaler, textScaleFactor), + super(children: WidgetSpan.extractFromInlineSpan(text, _effectiveTextScalerFrom(textScaler, textScaleFactor))); + + static TextScaler _effectiveTextScalerFrom(TextScaler textScaler, double textScaleFactor) { + return switch ((textScaler, textScaleFactor)) { + (final TextScaler scaler, 1.0) => scaler, + (TextScaler.noScaling, final double textScaleFactor) => TextScaler.linear(textScaleFactor), + (final TextScaler scaler, _) => scaler, + }; + } /// The text to display in this widget. final InlineSpan text; @@ -5772,11 +5788,22 @@ class RichText extends MultiChildRenderObjectWidget { /// How visual overflow should be handled. final TextOverflow overflow; + /// Deprecated. Will be removed in a future version of Flutter. Use + /// [textScaler] instead. + /// /// The number of font pixels for each logical pixel. /// /// For example, if the text scale factor is 1.5, text will be 50% larger than /// the specified font size. - final double textScaleFactor; + @Deprecated( + 'Use textScaler instead. ' + 'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. ' + 'This feature was deprecated after v3.12.0-2.0.pre.', + ) + double get textScaleFactor => textScaler.textScaleFactor; + + /// {@macro flutter.painting.textPainter.textScaler} + final TextScaler textScaler; /// An optional maximum number of lines for the text to span, wrapping if necessary. /// If the text exceeds the given number of lines, it will be truncated according @@ -5826,7 +5853,7 @@ class RichText extends MultiChildRenderObjectWidget { textDirection: textDirection ?? Directionality.of(context), softWrap: softWrap, overflow: overflow, - textScaleFactor: textScaleFactor, + textScaler: textScaler, maxLines: maxLines, strutStyle: strutStyle, textWidthBasis: textWidthBasis, @@ -5846,7 +5873,7 @@ class RichText extends MultiChildRenderObjectWidget { ..textDirection = textDirection ?? Directionality.of(context) ..softWrap = softWrap ..overflow = overflow - ..textScaleFactor = textScaleFactor + ..textScaler = textScaler ..maxLines = maxLines ..strutStyle = strutStyle ..textWidthBasis = textWidthBasis @@ -5863,7 +5890,7 @@ class RichText extends MultiChildRenderObjectWidget { properties.add(EnumProperty('textDirection', textDirection, defaultValue: null)); properties.add(FlagProperty('softWrap', value: softWrap, ifTrue: 'wrapping at box width', ifFalse: 'no wrapping except at line break characters', showName: true)); properties.add(EnumProperty('overflow', overflow, defaultValue: TextOverflow.clip)); - properties.add(DoubleProperty('textScaleFactor', textScaleFactor, defaultValue: 1.0)); + properties.add(DiagnosticsProperty('textScaler', textScaler, defaultValue: TextScaler.noScaling)); properties.add(IntProperty('maxLines', maxLines, ifNull: 'unlimited')); properties.add(EnumProperty('textWidthBasis', textWidthBasis, defaultValue: TextWidthBasis.parent)); properties.add(StringProperty('text', text.toPlainText())); diff --git a/packages/flutter/lib/src/widgets/editable_text.dart b/packages/flutter/lib/src/widgets/editable_text.dart index 859dfa89bd..d23229d536 100644 --- a/packages/flutter/lib/src/widgets/editable_text.dart +++ b/packages/flutter/lib/src/widgets/editable_text.dart @@ -752,7 +752,13 @@ class EditableText extends StatefulWidget { this.textAlign = TextAlign.start, this.textDirection, this.locale, + @Deprecated( + 'Use textScaler instead. ' + 'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. ' + 'This feature was deprecated after v3.12.0-2.0.pre.', + ) this.textScaleFactor, + this.textScaler, this.maxLines = 1, this.minLines, this.expands = false, @@ -1054,6 +1060,9 @@ class EditableText extends StatefulWidget { final Locale? locale; /// {@template flutter.widgets.editableText.textScaleFactor} + /// Deprecated. Will be removed in a future version of Flutter. Use + /// [textScaler] instead. + /// /// The number of font pixels for each logical pixel. /// /// For example, if the text scale factor is 1.5, text will be 50% larger than @@ -1062,8 +1071,16 @@ class EditableText extends StatefulWidget { /// Defaults to the [MediaQueryData.textScaleFactor] obtained from the ambient /// [MediaQuery], or 1.0 if there is no [MediaQuery] in scope. /// {@endtemplate} + @Deprecated( + 'Use textScaler instead. ' + 'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. ' + 'This feature was deprecated after v3.12.0-2.0.pre.', + ) final double? textScaleFactor; + /// {@macro flutter.painting.textPainter.textScaler} + final TextScaler? textScaler; + /// The color to use when painting the cursor. /// /// Cannot be null. @@ -2039,7 +2056,7 @@ class EditableText extends StatefulWidget { properties.add(EnumProperty('textAlign', textAlign, defaultValue: null)); properties.add(EnumProperty('textDirection', textDirection, defaultValue: null)); properties.add(DiagnosticsProperty('locale', locale, defaultValue: null)); - properties.add(DoubleProperty('textScaleFactor', textScaleFactor, defaultValue: null)); + properties.add(DiagnosticsProperty('textScaler', textScaler, defaultValue: null)); properties.add(IntProperty('maxLines', maxLines, defaultValue: 1)); properties.add(IntProperty('minLines', minLines, defaultValue: null)); properties.add(DiagnosticsProperty('expands', expands, defaultValue: false)); @@ -3890,11 +3907,17 @@ class EditableTextState extends State with AutomaticKeepAliveClien } final InlineSpan inlineSpan = renderEditable.text!; + final TextScaler effectiveTextScaler = switch ((widget.textScaler, widget.textScaleFactor)) { + (final TextScaler textScaler, _) => textScaler, + (null, final double textScaleFactor) => TextScaler.linear(textScaleFactor), + (null, null) => MediaQuery.textScalerOf(context), + }; + final _ScribbleCacheKey newCacheKey = _ScribbleCacheKey( inlineSpan: inlineSpan, textAlign: widget.textAlign, textDirection: _textDirection, - textScaleFactor: widget.textScaleFactor ?? MediaQuery.textScaleFactorOf(context), + textScaler: effectiveTextScaler, textHeightBehavior: widget.textHeightBehavior ?? DefaultTextHeightBehavior.maybeOf(context), locale: widget.locale, structStyle: widget.strutStyle, @@ -4588,6 +4611,12 @@ class EditableTextState extends State with AutomaticKeepAliveClien super.build(context); // See AutomaticKeepAliveClientMixin. final TextSelectionControls? controls = widget.selectionControls; + final TextScaler effectiveTextScaler = switch ((widget.textScaler, widget.textScaleFactor)) { + (final TextScaler textScaler, _) => textScaler, + (null, final double textScaleFactor) => TextScaler.linear(textScaleFactor), + (null, null) => MediaQuery.textScalerOf(context), + }; + return _CompositionCallback( compositeCallback: _compositeCallback, enabled: _hasInputConnection, @@ -4688,7 +4717,7 @@ class EditableTextState extends State with AutomaticKeepAliveClien selectionColor: _selectionOverlay?.spellCheckToolbarIsVisible ?? false ? _spellCheckConfiguration.misspelledSelectionColor ?? widget.selectionColor : widget.selectionColor, - textScaleFactor: widget.textScaleFactor ?? MediaQuery.textScaleFactorOf(context), + textScaler: effectiveTextScaler, textAlign: widget.textAlign, textDirection: _textDirection, locale: widget.locale, @@ -4814,7 +4843,7 @@ class _Editable extends MultiChildRenderObjectWidget { required this.expands, this.strutStyle, this.selectionColor, - required this.textScaleFactor, + required this.textScaler, required this.textAlign, required this.textDirection, this.locale, @@ -4835,7 +4864,7 @@ class _Editable extends MultiChildRenderObjectWidget { this.promptRectRange, this.promptRectColor, required this.clipBehavior, - }) : super(children: WidgetSpan.extractFromInlineSpan(inlineSpan, textScaleFactor)); + }) : super(children: WidgetSpan.extractFromInlineSpan(inlineSpan, textScaler)); final InlineSpan inlineSpan; final TextEditingValue value; @@ -4852,7 +4881,7 @@ class _Editable extends MultiChildRenderObjectWidget { final bool expands; final StrutStyle? strutStyle; final Color? selectionColor; - final double textScaleFactor; + final TextScaler textScaler; final TextAlign textAlign; final TextDirection textDirection; final Locale? locale; @@ -4893,7 +4922,7 @@ class _Editable extends MultiChildRenderObjectWidget { expands: expands, strutStyle: strutStyle, selectionColor: selectionColor, - textScaleFactor: textScaleFactor, + textScaler: textScaler, textAlign: textAlign, textDirection: textDirection, locale: locale ?? Localizations.maybeLocaleOf(context), @@ -4937,7 +4966,7 @@ class _Editable extends MultiChildRenderObjectWidget { ..expands = expands ..strutStyle = strutStyle ..selectionColor = selectionColor - ..textScaleFactor = textScaleFactor + ..textScaler = textScaler ..textAlign = textAlign ..textDirection = textDirection ..locale = locale ?? Localizations.maybeLocaleOf(context) @@ -4970,7 +4999,7 @@ class _ScribbleCacheKey { required this.inlineSpan, required this.textAlign, required this.textDirection, - required this.textScaleFactor, + required this.textScaler, required this.textHeightBehavior, required this.locale, required this.structStyle, @@ -4980,7 +5009,7 @@ class _ScribbleCacheKey { final TextAlign textAlign; final TextDirection textDirection; - final double textScaleFactor; + final TextScaler textScaler; final TextHeightBehavior? textHeightBehavior; final Locale? locale; final StrutStyle structStyle; @@ -4994,7 +5023,7 @@ class _ScribbleCacheKey { } final bool needsLayout = textAlign != other.textAlign || textDirection != other.textDirection - || textScaleFactor != other.textScaleFactor + || textScaler != other.textScaler || (textHeightBehavior ?? const TextHeightBehavior()) != (other.textHeightBehavior ?? const TextHeightBehavior()) || locale != other.locale || structStyle != other.structStyle @@ -5111,17 +5140,19 @@ class _ScribblePlaceholder extends WidgetSpan { final Size size; @override - void build(ui.ParagraphBuilder builder, { double textScaleFactor = 1.0, List? dimensions }) { + void build(ui.ParagraphBuilder builder, { + TextScaler textScaler = TextScaler.noScaling, + List? dimensions, + }) { assert(debugAssertIsValid()); final bool hasStyle = style != null; if (hasStyle) { - builder.pushStyle(style!.getTextStyle(textScaleFactor: textScaleFactor)); + builder.pushStyle(style!.getTextStyle(textScaler: textScaler)); } builder.addPlaceholder( - size.width, - size.height, + size.width * textScaler.textScaleFactor, + size.height * textScaler.textScaleFactor, alignment, - scale: textScaleFactor, ); if (hasStyle) { builder.pop(); diff --git a/packages/flutter/lib/src/widgets/media_query.dart b/packages/flutter/lib/src/widgets/media_query.dart index 0714708e14..1c80b4d2e2 100644 --- a/packages/flutter/lib/src/widgets/media_query.dart +++ b/packages/flutter/lib/src/widgets/media_query.dart @@ -30,8 +30,8 @@ enum Orientation { /// /// [MediaQuery] contains a large number of related properties. Widgets frequently /// depend on only a few of these attributes. For example, a widget that needs to -/// rebuild when the [MediaQueryData.textScaleFactor] changes does not need to -/// be notified when the [MediaQueryData.size] changes. Specifying an aspect avoids +/// rebuild when the [MediaQueryData.textScaler] changes does not need to be +/// notified when the [MediaQueryData.size] changes. Specifying an aspect avoids /// unnecessary rebuilds. enum _MediaQueryAspect { /// Specifies the aspect corresponding to [MediaQueryData.size]. @@ -42,6 +42,8 @@ enum _MediaQueryAspect { devicePixelRatio, /// Specifies the aspect corresponding to [MediaQueryData.textScaleFactor]. textScaleFactor, + /// Specifies the aspect corresponding to [MediaQueryData.textScaler]. + textScaler, /// Specifies the aspect corresponding to [MediaQueryData.platformBrightness]. platformBrightness, /// Specifies the aspect corresponding to [MediaQueryData.padding]. @@ -140,12 +142,20 @@ enum _MediaQueryAspect { class MediaQueryData { /// Creates data for a media query with explicit values. /// - /// Consider using [MediaQueryData.fromView] to create data based on a - /// [dart:ui.FlutterView]. + /// In a typical application, calling this constructor directly is rarely + /// needed. Consider using [MediaQueryData.fromView] to create data based on a + /// [dart:ui.FlutterView], or [MediaQueryData.copyWith] to create a new copy + /// of [MediaQueryData] with updated properties from a base [MediaQueryData]. const MediaQueryData({ this.size = Size.zero, this.devicePixelRatio = 1.0, - this.textScaleFactor = 1.0, + @Deprecated( + 'Use textScaler instead. ' + 'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. ' + 'This feature was deprecated after v3.12.0-2.0.pre.', + ) + double textScaleFactor = 1.0, + TextScaler textScaler = _kUnspecifiedTextScaler, this.platformBrightness = Brightness.light, this.padding = EdgeInsets.zero, this.viewInsets = EdgeInsets.zero, @@ -161,7 +171,12 @@ class MediaQueryData { this.navigationMode = NavigationMode.traditional, this.gestureSettings = const DeviceGestureSettings(touchSlop: kTouchSlop), this.displayFeatures = const [], - }); + }) : _textScaleFactor = textScaleFactor, + _textScaler = textScaler, + assert( + identical(textScaler, _kUnspecifiedTextScaler) || textScaleFactor == 1.0, + 'textScaleFactor is deprecated and cannot be specified when textScaler is specified.', + ); /// Deprecated. Use [MediaQueryData.fromView] instead. /// @@ -212,7 +227,8 @@ class MediaQueryData { MediaQueryData.fromView(ui.FlutterView view, {MediaQueryData? platformData}) : size = view.physicalSize / view.devicePixelRatio, devicePixelRatio = view.devicePixelRatio, - textScaleFactor = platformData?.textScaleFactor ?? view.platformDispatcher.textScaleFactor, + _textScaleFactor = 1.0, // _textScaler is the source of truth. + _textScaler = _textScalerFromView(view, platformData), platformBrightness = platformData?.platformBrightness ?? view.platformDispatcher.platformBrightness, padding = EdgeInsets.fromViewPadding(view.padding, view.devicePixelRatio), viewPadding = EdgeInsets.fromViewPadding(view.viewPadding, view.devicePixelRatio), @@ -229,6 +245,11 @@ class MediaQueryData { gestureSettings = DeviceGestureSettings.fromView(view), displayFeatures = view.displayFeatures; + static TextScaler _textScalerFromView(ui.FlutterView view, MediaQueryData? platformData) { + final double scaleFactor = platformData?.textScaleFactor ?? view.platformDispatcher.textScaleFactor; + return scaleFactor == 1.0 ? TextScaler.noScaling : TextScaler.linear(scaleFactor); + } + /// The size of the media in logical pixels (e.g, the size of the screen). /// /// Logical pixels are roughly the same visual size across devices. Physical @@ -261,6 +282,9 @@ class MediaQueryData { /// the Nexus 6 has a device pixel ratio of 3.5. final double devicePixelRatio; + /// Deprecated. Will be removed in a future version of Flutter. Use + /// [textScaler] instead. + /// /// The number of font pixels for each logical pixel. /// /// For example, if the text scale factor is 1.5, text will be 50% larger than @@ -270,7 +294,44 @@ class MediaQueryData { /// /// * [MediaQuery.textScaleFactorOf], a method to find and depend on the /// textScaleFactor defined for a [BuildContext]. - final double textScaleFactor; + @Deprecated( + 'Use textScaler instead. ' + 'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. ' + 'This feature was deprecated after v3.12.0-2.0.pre.', + ) + double get textScaleFactor => textScaler.textScaleFactor; + // TODO(LongCatIsLooong): remove this after textScaleFactor is removed. To + // maintain backward compatibility and also keep the const constructor this + // has to be kept as a private field. + // https://github.com/flutter/flutter/issues/128825 + final double _textScaleFactor; + + /// The font scaling strategy to use for laying out textual contents. + /// + /// If this [MediaQueryData] is created by the [MediaQueryData.fromView] + /// constructor, this property reflects the platform's preferred text scaling + /// strategy, and may change as the user changes the scaling factor in the + /// operating system's accessibility settings. + /// + /// See also: + /// + /// * [MediaQuery.textScalerOf], a method to find and depend on the + /// [textScaler] defined for a [BuildContext]. + /// * [TextPainter], a class that lays out and paints text. + TextScaler get textScaler { + // The constructor was called with an explicitly specified textScaler value, + // we assume the caller is migrated and ignore _textScaleFactor. + if (!identical(_kUnspecifiedTextScaler, _textScaler)) { + return _textScaler; + } + return _textScaleFactor == 1.0 + // textScaleFactor and textScaler from the constructor are consistent. + ? TextScaler.noScaling + // The constructor was called with an explicitly specified textScaleFactor, + // we assume the caller is unmigrated and ignore _textScaler. + : TextScaler.linear(_textScaleFactor); + } + final TextScaler _textScaler; /// The current brightness mode of the host platform. /// @@ -490,10 +551,19 @@ class MediaQueryData { /// Creates a copy of this media query data but with the given fields replaced /// with the new values. + /// + /// The `textScaler` parameter and `textScaleFactor` parameter must not be + /// both specified. MediaQueryData copyWith({ Size? size, double? devicePixelRatio, + @Deprecated( + 'Use textScaler instead. ' + 'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. ' + 'This feature was deprecated after v3.12.0-2.0.pre.', + ) double? textScaleFactor, + TextScaler? textScaler, Brightness? platformBrightness, EdgeInsets? padding, EdgeInsets? viewPadding, @@ -510,10 +580,14 @@ class MediaQueryData { DeviceGestureSettings? gestureSettings, List? displayFeatures, }) { + assert(textScaleFactor == null || textScaler == null); + if (textScaleFactor != null) { + textScaler ??= TextScaler.linear(textScaleFactor); + } return MediaQueryData( size: size ?? this.size, devicePixelRatio: devicePixelRatio ?? this.devicePixelRatio, - textScaleFactor: textScaleFactor ?? this.textScaleFactor, + textScaler: textScaler ?? this.textScaler, platformBrightness: platformBrightness ?? this.platformBrightness, padding: padding ?? this.padding, viewPadding: viewPadding ?? this.viewPadding, @@ -750,7 +824,7 @@ class MediaQueryData { final List properties = [ 'size: $size', 'devicePixelRatio: ${devicePixelRatio.toStringAsFixed(1)}', - 'textScaleFactor: ${textScaleFactor.toStringAsFixed(1)}', + 'textScaler: $textScaler', 'platformBrightness: $platformBrightness', 'padding: $padding', 'viewPadding: $viewPadding', @@ -1002,6 +1076,64 @@ class MediaQuery extends InheritedModel<_MediaQueryAspect> { ); } + /// Wraps the `child` in a [MediaQuery] with its [MediaQueryData.textScaler] + /// set to [TextScaler.noScaling]. + /// + /// The returned widget must be inserted in a widget tree below an existing + /// [MediaQuery] widget. + /// + /// This can be used to prevent, for example, icon fonts from scaling as the + /// user adjusts the platform's text scaling value. + static Widget withNoTextScaling({ + Key? key, + required Widget child, + }) { + return Builder( + key: key, + builder: (BuildContext context) { + assert(debugCheckHasMediaQuery(context)); + return MediaQuery( + data: MediaQuery.of(context).copyWith(textScaler: TextScaler.noScaling), + child: child, + ); + }, + ); + } + + /// Wraps the `child` in a [MediaQuery] and applies [TextScaler.clamp] on the + /// current [MediaQueryData.textScaler]. + /// + /// The returned widget must be inserted in a widget tree below an existing + /// [MediaQuery] widget. + /// + /// This is a convenience function to restrict the range of the scaled text + /// size to `[minScaleFactor * fontSize, maxScaleFactor * fontSize]` (to + /// prevent excessive text scaling that would break the UI, for example). When + /// `minScaleFactor` equals `maxScaleFactor`, the scaler becomes + /// `TextScaler.linear(minScaleFactor)`. + static Widget withClampedTextScaling({ + Key? key, + double minScaleFactor = 0.0, + double maxScaleFactor = double.infinity, + required Widget child, + }) { + assert(maxScaleFactor >= minScaleFactor); + assert(!maxScaleFactor.isNaN); + assert(minScaleFactor.isFinite); + assert(minScaleFactor >= 0); + + return Builder(builder: (BuildContext context) { + assert(debugCheckHasMediaQuery(context)); + final MediaQueryData data = MediaQuery.of(context); + return MediaQuery( + data: data.copyWith( + textScaler: data.textScaler.clamp(minScaleFactor: minScaleFactor, maxScaleFactor: maxScaleFactor), + ), + child: child, + ); + }); + } + /// Contains information about the current media. /// /// For example, the [MediaQueryData.size] property contains the width and @@ -1126,20 +1258,53 @@ class MediaQuery extends InheritedModel<_MediaQueryAspect> { /// the [MediaQueryData.devicePixelRatio] property of the ancestor [MediaQuery] changes. static double? maybeDevicePixelRatioOf(BuildContext context) => _maybeOf(context, _MediaQueryAspect.devicePixelRatio)?.devicePixelRatio; + /// Deprecated. Will be removed in a future version of Flutter. Use + /// [maybeTextScalerOf] instead. + /// /// Returns textScaleFactor for the nearest MediaQuery ancestor or /// 1.0, if no such ancestor exists. /// /// Use of this method will cause the given [context] to rebuild any time that /// the [MediaQueryData.textScaleFactor] property of the ancestor [MediaQuery] changes. + @Deprecated( + 'Use textScalerOf instead. ' + 'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. ' + 'This feature was deprecated after v3.12.0-2.0.pre.', + ) static double textScaleFactorOf(BuildContext context) => maybeTextScaleFactorOf(context) ?? 1.0; + /// Deprecated. Will be removed in a future version of Flutter. Use + /// [maybeTextScalerOf] instead. + /// /// Returns textScaleFactor for the nearest MediaQuery ancestor or /// null, if no such ancestor exists. /// /// Use of this method will cause the given [context] to rebuild any time that - /// the [MediaQueryData.textScaleFactor] property of the ancestor [MediaQuery] changes. + /// the [MediaQueryData.textScaleFactor] property of the ancestor [MediaQuery] + /// changes. + @Deprecated( + 'Use maybeTextScalerOf instead. ' + 'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. ' + 'This feature was deprecated after v3.12.0-2.0.pre.', + ) static double? maybeTextScaleFactorOf(BuildContext context) => _maybeOf(context, _MediaQueryAspect.textScaleFactor)?.textScaleFactor; + /// Returns the [TextScaler] for the nearest [MediaQuery] ancestor or null if + /// no such ancestor exists. + /// + /// Use of this method will cause the given [context] to rebuild any time that + /// the [MediaQueryData.textScaler] property of the ancestor [MediaQuery] + /// changes. + static TextScaler textScalerOf(BuildContext context) => maybeTextScalerOf(context) ?? TextScaler.noScaling; + + /// Returns the [TextScaler] for the nearest [MediaQuery] ancestor or + /// [TextScaler.noScaling] if no such ancestor exists. + /// + /// Use of this method will cause the given [context] to rebuild any time that + /// the [MediaQueryData.textScaler] property of the ancestor [MediaQuery] + /// changes. + static TextScaler? maybeTextScalerOf(BuildContext context) => _maybeOf(context, _MediaQueryAspect.textScaler)?.textScaler; + /// Returns platformBrightness for the nearest MediaQuery ancestor or /// [Brightness.light], if no such ancestor exists. /// @@ -1407,6 +1572,10 @@ class MediaQuery extends InheritedModel<_MediaQueryAspect> { if (data.textScaleFactor != oldWidget.data.textScaleFactor) { return true; } + case _MediaQueryAspect.textScaler: + if (data.textScaler != oldWidget.data.textScaler) { + return true; + } case _MediaQueryAspect.platformBrightness: if (data.platformBrightness != oldWidget.data.platformBrightness) { return true; @@ -1620,3 +1789,19 @@ class _MediaQueryFromViewState extends State<_MediaQueryFromView> with WidgetsBi ); } } + +const TextScaler _kUnspecifiedTextScaler = _UnspecifiedTextScaler(); +// TODO(LongCatIsLooong): Remove once `MediaQueryData.textScaleFactor` is +// removed: https://github.com/flutter/flutter/issues/128825. +class _UnspecifiedTextScaler implements TextScaler { + const _UnspecifiedTextScaler(); + + @override + TextScaler clamp({double minScaleFactor = 0, double maxScaleFactor = double.infinity}) => throw UnimplementedError(); + + @override + double scale(double fontSize) => throw UnimplementedError(); + + @override + double get textScaleFactor => throw UnimplementedError(); +} diff --git a/packages/flutter/lib/src/widgets/text.dart b/packages/flutter/lib/src/widgets/text.dart index 45111223b0..b1870e1a94 100644 --- a/packages/flutter/lib/src/widgets/text.dart +++ b/packages/flutter/lib/src/widgets/text.dart @@ -435,13 +435,23 @@ class Text extends StatelessWidget { this.locale, this.softWrap, this.overflow, + @Deprecated( + 'Use textScaler instead. ' + 'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. ' + 'This feature was deprecated after v3.12.0-2.0.pre.', + ) this.textScaleFactor, + this.textScaler, this.maxLines, this.semanticsLabel, this.textWidthBasis, this.textHeightBehavior, this.selectionColor, - }) : textSpan = null; + }) : textSpan = null, + assert( + textScaler == null || textScaleFactor == null, + 'textScaleFactor is deprecated and cannot be specified when textScaler is specified.', + ); /// Creates a text widget with a [InlineSpan]. /// @@ -463,13 +473,23 @@ class Text extends StatelessWidget { this.locale, this.softWrap, this.overflow, + @Deprecated( + 'Use textScaler instead. ' + 'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. ' + 'This feature was deprecated after v3.12.0-2.0.pre.', + ) this.textScaleFactor, + this.textScaler, this.maxLines, this.semanticsLabel, this.textWidthBasis, this.textHeightBehavior, this.selectionColor, - }) : data = null; + }) : data = null, + assert( + textScaler == null || textScaleFactor == null, + 'textScaleFactor is deprecated and cannot be specified when textScaler is specified.', + ); /// The text to display. /// @@ -529,6 +549,9 @@ class Text extends StatelessWidget { /// from the nearest [DefaultTextStyle] ancestor will be used. final TextOverflow? overflow; + /// Deprecated. Will be removed in a future version of Flutter. Use + /// [textScaler] instead. + /// /// The number of font pixels for each logical pixel. /// /// For example, if the text scale factor is 1.5, text will be 50% larger than @@ -537,8 +560,16 @@ class Text extends StatelessWidget { /// The value given to the constructor as textScaleFactor. If null, will /// use the [MediaQueryData.textScaleFactor] obtained from the ambient /// [MediaQuery], or 1.0 if there is no [MediaQuery] in scope. + @Deprecated( + 'Use textScaler instead. ' + 'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. ' + 'This feature was deprecated after v3.12.0-2.0.pre.', + ) final double? textScaleFactor; + /// {@macro flutter.painting.textPainter.textScaler} + final TextScaler? textScaler; + /// An optional maximum number of lines for the text to span, wrapping if necessary. /// If the text exceeds the given number of lines, it will be truncated according /// to [overflow]. @@ -595,13 +626,20 @@ class Text extends StatelessWidget { effectiveTextStyle = effectiveTextStyle!.merge(const TextStyle(fontWeight: FontWeight.bold)); } final SelectionRegistrar? registrar = SelectionContainer.maybeOf(context); + final TextScaler textScaler = switch ((this.textScaler, textScaleFactor)) { + (final TextScaler textScaler, _) => textScaler, + // For unmigrated apps, fall back to textScaleFactor. + (null, final double textScaleFactor) => TextScaler.linear(textScaleFactor), + (null, null) => MediaQuery.textScalerOf(context), + }; + Widget result = RichText( textAlign: textAlign ?? defaultTextStyle.textAlign ?? TextAlign.start, textDirection: textDirection, // RichText uses Directionality.of to obtain a default if this is null. locale: locale, // RichText uses Localizations.localeOf to obtain a default if this is null softWrap: softWrap ?? defaultTextStyle.softWrap, overflow: overflow ?? effectiveTextStyle?.overflow ?? defaultTextStyle.overflow, - textScaleFactor: textScaleFactor ?? MediaQuery.textScaleFactorOf(context), + textScaler: textScaler, maxLines: maxLines ?? defaultTextStyle.maxLines, strutStyle: strutStyle, textWidthBasis: textWidthBasis ?? defaultTextStyle.textWidthBasis, diff --git a/packages/flutter/lib/src/widgets/widget_span.dart b/packages/flutter/lib/src/widgets/widget_span.dart index 776d4087ce..34afb66f3a 100644 --- a/packages/flutter/lib/src/widgets/widget_span.dart +++ b/packages/flutter/lib/src/widgets/widget_span.dart @@ -10,6 +10,8 @@ import 'package:flutter/rendering.dart'; import 'basic.dart'; import 'framework.dart'; +const double _kEngineDefaultFontSize = 14.0; + // Examples can assume: // late WidgetSpan myWidgetSpan; @@ -90,17 +92,28 @@ class WidgetSpan extends PlaceholderSpan { /// Helper function for extracting [WidgetSpan]s in preorder, from the given /// [InlineSpan] as a list of widgets. /// - /// The `textScaleFactor` is the the number of font pixels for each logical - /// pixel. + /// The `textScaler` is the scaling strategy for scaling the content. /// /// This function is used by [EditableText] and [RichText] so calling it /// directly is rarely necessary. - static List extractFromInlineSpan(InlineSpan span, double textScaleFactor) { + static List extractFromInlineSpan(InlineSpan span, TextScaler textScaler) { final List widgets = []; + // _kEngineDefaultFontSize is the default font size to use when none of the + // ancestor spans specifies one. + final List fontSizeStack = [_kEngineDefaultFontSize]; int index = 0; // This assumes an InlineSpan tree's logical order is equivalent to preorder. - span.visitChildren((InlineSpan span) { + bool visitSubtree(InlineSpan span) { + final double? fontSizeToPush = switch (span.style?.fontSize) { + final double size when size != fontSizeStack.last => size, + _ => null, + }; + if (fontSizeToPush != null) { + fontSizeStack.add(fontSizeToPush); + } if (span is WidgetSpan) { + final double fontSize = fontSizeStack.last; + final double textScaleFactor = fontSize == 0 ? 0 : textScaler.scale(fontSize) / fontSize; widgets.add( _WidgetSpanParentData( span: span, @@ -115,8 +128,15 @@ class WidgetSpan extends PlaceholderSpan { span is WidgetSpan || span is! PlaceholderSpan, '$span is a PlaceholderSpan but not a WidgetSpan subclass. This is currently not supported.', ); + span.visitDirectChildren(visitSubtree); + if (fontSizeToPush != null) { + final double poppedFontSize = fontSizeStack.removeLast(); + assert(fontSizeStack.isNotEmpty); + assert(poppedFontSize == fontSizeToPush); + } return true; - }); + } + visitSubtree(span); return widgets; } @@ -130,14 +150,17 @@ class WidgetSpan extends PlaceholderSpan { /// in-order mapping of widget to laid-out dimensions. If no such dimension /// is provided, the widget will be skipped. /// - /// The `textScaleFactor` will be applied to the laid-out size of the widget. + /// The `textScaler` will be applied to the laid-out size of the widget. @override - void build(ui.ParagraphBuilder builder, { double textScaleFactor = 1.0, List? dimensions }) { + void build(ui.ParagraphBuilder builder, { + TextScaler textScaler = TextScaler.noScaling, + List? dimensions, + }) { assert(debugAssertIsValid()); assert(dimensions != null); final bool hasStyle = style != null; if (hasStyle) { - builder.pushStyle(style!.getTextStyle(textScaleFactor: textScaleFactor)); + builder.pushStyle(style!.getTextStyle(textScaler: textScaler)); } assert(builder.placeholderCount < dimensions!.length); final PlaceholderDimensions currentDimensions = dimensions![builder.placeholderCount]; diff --git a/packages/flutter/test/cupertino/material/tab_scaffold_test.dart b/packages/flutter/test/cupertino/material/tab_scaffold_test.dart index ed211846d6..1014b4137e 100644 --- a/packages/flutter/test/cupertino/material/tab_scaffold_test.dart +++ b/packages/flutter/test/cupertino/material/tab_scaffold_test.dart @@ -311,10 +311,10 @@ void main() { ); expect(barItems.length, greaterThan(0)); - expect(barItems.any((RichText t) => t.textScaleFactor != 1), isFalse); + expect(barItems, isNot(contains(predicate((RichText t) => t.textScaler != TextScaler.noScaling)))); expect(contents.length, greaterThan(0)); - expect(contents.any((RichText t) => t.textScaleFactor != 99), isFalse); + expect(contents, isNot(contains(predicate((RichText t) => t.textScaler != const TextScaler.linear(99.0))))); }); } diff --git a/packages/flutter/test/cupertino/nav_bar_test.dart b/packages/flutter/test/cupertino/nav_bar_test.dart index 9b7532afd0..4f86b395d8 100644 --- a/packages/flutter/test/cupertino/nav_bar_test.dart +++ b/packages/flutter/test/cupertino/nav_bar_test.dart @@ -1230,10 +1230,10 @@ void main() { ); expect(barItems.length, greaterThan(0)); - expect(barItems.any((RichText t) => t.textScaleFactor != 1), isFalse); + expect(barItems, isNot(contains(predicate((RichText t) => t.textScaler != TextScaler.noScaling)))); expect(contents.length, greaterThan(0)); - expect(contents.any((RichText t) => t.textScaleFactor != 99), isFalse); + expect(contents, isNot(contains(predicate((RichText t) => t.textScaler != const TextScaler.linear(99.0))))); // Also works with implicitly added widgets. tester.state(find.byType(Navigator)).push(CupertinoPageRoute( diff --git a/packages/flutter/test/cupertino/scaffold_test.dart b/packages/flutter/test/cupertino/scaffold_test.dart index 41b40c07b1..833c484f26 100644 --- a/packages/flutter/test/cupertino/scaffold_test.dart +++ b/packages/flutter/test/cupertino/scaffold_test.dart @@ -554,6 +554,6 @@ void main() { expect(richTextList.length, greaterThan(0)); expect(richTextList.any((RichText text) => text.textScaleFactor != 1), isFalse); - expect(tester.widget(find.descendant(of: find.text('content'), matching: find.byType(RichText))).textScaleFactor, 99); + expect(tester.widget(find.descendant(of: find.text('content'), matching: find.byType(RichText))).textScaler, const TextScaler.linear(99.0)); }); } diff --git a/packages/flutter/test/cupertino/tab_scaffold_test.dart b/packages/flutter/test/cupertino/tab_scaffold_test.dart index 9e76489704..a8a43b5102 100644 --- a/packages/flutter/test/cupertino/tab_scaffold_test.dart +++ b/packages/flutter/test/cupertino/tab_scaffold_test.dart @@ -1106,10 +1106,10 @@ void main() { ); expect(barItems.length, greaterThan(0)); - expect(barItems.any((RichText t) => t.textScaleFactor != 1), isFalse); + expect(barItems, isNot(contains(predicate((RichText t) => t.textScaler != TextScaler.noScaling)))); expect(contents.length, greaterThan(0)); - expect(contents.any((RichText t) => t.textScaleFactor != 99), isFalse); + expect(contents, isNot(contains(predicate((RichText t) => t.textScaler != const TextScaler.linear(99.0))))); }); testWidgets('state restoration', (WidgetTester tester) async { diff --git a/packages/flutter/test/material/app_bar_test.dart b/packages/flutter/test/material/app_bar_test.dart index b9234fbe60..ecdfd3d802 100644 --- a/packages/flutter/test/material/app_bar_test.dart +++ b/packages/flutter/test/material/app_bar_test.dart @@ -1685,6 +1685,36 @@ void main() { expect(appBarHeight(tester), kToolbarHeight + 100.0); }); + testWidgets('AppBar.title sees the correct padding from MediaQuery', (WidgetTester tester) async { + bool titleBuilt = false; + await tester.pumpWidget( + Localizations( + locale: const Locale('en', 'US'), + delegates: const >[ + DefaultMaterialLocalizations.delegate, + DefaultWidgetsLocalizations.delegate, + ], + child: Directionality( + textDirection: TextDirection.ltr, + child: MediaQuery( + data: const MediaQueryData(padding: EdgeInsets.fromLTRB(12, 34, 56, 78)), + child: Scaffold( + appBar: AppBar( + title: Builder(builder: (BuildContext context) { + titleBuilt = true; + final EdgeInsets padding = MediaQuery.paddingOf(context); + expect(padding, EdgeInsets.zero); + return const Text('heh'); + }), + ), + ), + ), + ), + ), + ); + expect(titleBuilt, isTrue); + }); + testWidgets('AppBar updates when you add a drawer', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( diff --git a/packages/flutter/test/material/app_test.dart b/packages/flutter/test/material/app_test.dart index 734aa878be..d4dad0cb59 100644 --- a/packages/flutter/test/material/app_test.dart +++ b/packages/flutter/test/material/app_test.dart @@ -465,15 +465,14 @@ void main() { }); testWidgets('Can get text scale from media query', (WidgetTester tester) async { - double? textScaleFactor; + TextScaler? textScaler; await tester.pumpWidget(MaterialApp( home: Builder(builder:(BuildContext context) { - textScaleFactor = MediaQuery.textScaleFactorOf(context); + textScaler = MediaQuery.textScalerOf(context); return Container(); }), )); - expect(textScaleFactor, isNotNull); - expect(textScaleFactor, equals(1.0)); + expect(textScaler, TextScaler.noScaling); }); testWidgets('MaterialApp.navigatorKey', (WidgetTester tester) async { diff --git a/packages/flutter/test/material/theme_test.dart b/packages/flutter/test/material/theme_test.dart index 3a907941c3..1cbcbca300 100644 --- a/packages/flutter/test/material/theme_test.dart +++ b/packages/flutter/test/material/theme_test.dart @@ -1140,6 +1140,7 @@ class _TextStyleProxy implements TextStyle { TextAlign? textAlign, TextDirection? textDirection, double textScaleFactor = 1.0, + TextScaler textScaler = TextScaler.noScaling, String? ellipsis, int? maxLines, ui.TextHeightBehavior? textHeightBehavior, @@ -1155,7 +1156,7 @@ class _TextStyleProxy implements TextStyle { } @override - ui.TextStyle getTextStyle({ double textScaleFactor = 1.0 }) { + ui.TextStyle getTextStyle({ double textScaleFactor = 1.0, TextScaler textScaler = TextScaler.noScaling }) { throw UnimplementedError(); } diff --git a/packages/flutter/test/painting/text_painter_test.dart b/packages/flutter/test/painting/text_painter_test.dart index f0b76fc0b9..55c7ec50e0 100644 --- a/packages/flutter/test/painting/text_painter_test.dart +++ b/packages/flutter/test/painting/text_painter_test.dart @@ -400,27 +400,27 @@ void main() { painter.dispose(); }); - test('TextPainter textScaleFactor test', () { + test('TextPainter textScaler test', () { final TextPainter painter = TextPainter( text: const TextSpan( text: 'X', style: TextStyle(inherit: false, fontSize: 10.0), ), textDirection: TextDirection.ltr, - textScaleFactor: 2.0, + textScaler: const TextScaler.linear(2.0), ); painter.layout(); expect(painter.size, const Size(20.0, 20.0)); painter.dispose(); }); - test('TextPainter textScaleFactor null style test', () { + test('TextPainter textScaler null style test', () { final TextPainter painter = TextPainter( text: const TextSpan( text: 'X', ), textDirection: TextDirection.ltr, - textScaleFactor: 2.0, + textScaler: const TextScaler.linear(2.0), ); painter.layout(); expect(painter.size, const Size(28.0, 28.0)); diff --git a/packages/flutter/test/painting/text_scaler_test.dart b/packages/flutter/test/painting/text_scaler_test.dart new file mode 100644 index 0000000000..6083f15ce2 --- /dev/null +++ b/packages/flutter/test/painting/text_scaler_test.dart @@ -0,0 +1,37 @@ +// 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:flutter/painting.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Linear TextScaler', () { + test('equality', () { + const TextScaler a = TextScaler.linear(3.0); + final TextScaler b = TextScaler.noScaling.clamp(minScaleFactor: 3.0); + // Creates a non-const TextScaler instance. + final TextScaler c = TextScaler.linear(3.0); // ignore: prefer_const_constructors + final TextScaler d = TextScaler.noScaling + .clamp(minScaleFactor: 1, maxScaleFactor: 5) + .clamp(minScaleFactor: 3, maxScaleFactor: 6); + + final List list = [a, b, c, d]; + for (final TextScaler lhs in list) { + expect(list, everyElement(lhs)); + } + }); + + test('clamping', () { + expect(TextScaler.noScaling.clamp(minScaleFactor: 3.0), const TextScaler.linear(3.0)); + expect(const TextScaler.linear(5.0).clamp(maxScaleFactor: 3.0), const TextScaler.linear(3.0)); + expect(const TextScaler.linear(5.0).clamp(maxScaleFactor: 3.0), const TextScaler.linear(3.0)); + expect(const TextScaler.linear(5.0).clamp(minScaleFactor: 3.0, maxScaleFactor: 3.0), const TextScaler.linear(3.0)); + // Asserts when min > max. + expect( + () => TextScaler.noScaling.clamp(minScaleFactor: 5.0, maxScaleFactor: 4.0), + throwsA(isA().having((AssertionError error) => error.toString(), 'message', contains('maxScaleFactor >= minScaleFactor'))), + ); + }); + }); +} diff --git a/packages/flutter/test/painting/text_style_test.dart b/packages/flutter/test/painting/text_style_test.dart index d2bd4c4b1e..1658eb5913 100644 --- a/packages/flutter/test/painting/text_style_test.dart +++ b/packages/flutter/test/painting/text_style_test.dart @@ -503,9 +503,9 @@ void main() { expect(TextStyle.lerp(redPaintTextStyle, bluePaintTextStyle, .75)!.background!.color, blue); }); - test('TextStyle strut textScaleFactor', () { + test('TextStyle strut textScaler', () { const TextStyle style0 = TextStyle(fontSize: 10); - final ui.ParagraphStyle paragraphStyle0 = style0.getParagraphStyle(textScaleFactor: 2.5); + final ui.ParagraphStyle paragraphStyle0 = style0.getParagraphStyle(textScaler: const TextScaler.linear(2.5)); const TextStyle style1 = TextStyle(fontSize: 25); final ui.ParagraphStyle paragraphStyle1 = style1.getParagraphStyle(); diff --git a/packages/flutter/test/painting/widget_span_test.dart b/packages/flutter/test/painting/widget_span_test.dart deleted file mode 100644 index 632920754e..0000000000 --- a/packages/flutter/test/painting/widget_span_test.dart +++ /dev/null @@ -1,28 +0,0 @@ -// 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:flutter/widgets.dart'; -import 'package:flutter_test/flutter_test.dart'; - -void main() { - test('WidgetSpan codeUnitAt', () { - const InlineSpan span = WidgetSpan(child: SizedBox()); - expect(span.codeUnitAt(-1), isNull); - expect(span.codeUnitAt(0), PlaceholderSpan.placeholderCodeUnit); - expect(span.codeUnitAt(1), isNull); - expect(span.codeUnitAt(2), isNull); - - const InlineSpan nestedSpan = TextSpan( - text: 'AAA', - children: [span, span], - ); - expect(nestedSpan.codeUnitAt(-1), isNull); - expect(nestedSpan.codeUnitAt(0), 65); - expect(nestedSpan.codeUnitAt(1), 65); - expect(nestedSpan.codeUnitAt(2), 65); - expect(nestedSpan.codeUnitAt(3), PlaceholderSpan.placeholderCodeUnit); - expect(nestedSpan.codeUnitAt(4), PlaceholderSpan.placeholderCodeUnit); - expect(nestedSpan.codeUnitAt(5), isNull); - }); -} diff --git a/packages/flutter/test/rendering/editable_test.dart b/packages/flutter/test/rendering/editable_test.dart index 0a31aa54e1..118f1adbf6 100644 --- a/packages/flutter/test/rendering/editable_test.dart +++ b/packages/flutter/test/rendering/editable_test.dart @@ -230,7 +230,6 @@ void main() { ' │ maxLines: 1\n' ' │ minLines: null\n' ' │ selectionColor: null\n' - ' │ textScaleFactor: 1.0\n' ' │ locale: ja_JP\n' ' │ selection: null\n' ' │ offset: _FixedViewportOffset#00000(offset: 0.0)\n' @@ -331,7 +330,7 @@ void main() { ), )); - editable.textScaleFactor = 2; + editable.textScaler = const TextScaler.linear(2.0); pumpFrame(phase: EnginePhase.compositingBits); // Now the caret height is much bigger due to the bigger font scale. @@ -454,7 +453,7 @@ void main() { ), )); - editable.textScaleFactor = 2; + editable.textScaler = const TextScaler.linear(2.0); pumpFrame(phase: EnginePhase.compositingBits); // Now the caret height is much bigger due to the bigger font scale. @@ -1631,7 +1630,7 @@ void main() { selection: const TextSelection.collapsed(offset: 3), maxLines: 2, minLines: 2, - textScaleFactor: 2.0, + textScaler: const TextScaler.linear(2.0), children: renderBoxes, ); _applyParentData(renderBoxes, editable.text!); diff --git a/packages/flutter/test/rendering/paragraph_test.dart b/packages/flutter/test/rendering/paragraph_test.dart index 8ae7c59ec1..f7d8eba8c2 100644 --- a/packages/flutter/test/rendering/paragraph_test.dart +++ b/packages/flutter/test/rendering/paragraph_test.dart @@ -406,7 +406,7 @@ void main() { expect(paragraph.debugNeedsPaint, isFalse); }); - test('nested TextSpans in paragraph handle textScaleFactor correctly.', () { + test('nested TextSpans in paragraph handle linear textScaler correctly.', () { const TextSpan testSpan = TextSpan( text: 'a', style: TextStyle( @@ -430,7 +430,7 @@ void main() { final RenderParagraph paragraph = RenderParagraph( testSpan, textDirection: TextDirection.ltr, - textScaleFactor: 1.3, + textScaler: const TextScaler.linear(1.3), ); paragraph.layout(const BoxConstraints()); expect(paragraph.size.width, 78.0); diff --git a/packages/flutter/test/widgets/media_query_test.dart b/packages/flutter/test/widgets/media_query_test.dart index 2a24e45ca0..38793a3948 100644 --- a/packages/flutter/test/widgets/media_query_test.dart +++ b/packages/flutter/test/widgets/media_query_test.dart @@ -181,7 +181,7 @@ void main() { expect(data.hashCode, data.copyWith().hashCode); expect(data.size, tester.view.physicalSize / tester.view.devicePixelRatio); expect(data.devicePixelRatio, tester.view.devicePixelRatio); - expect(data.textScaleFactor, platformData.textScaleFactor); + expect(data.textScaler, TextScaler.linear(platformData.textScaleFactor)); expect(data.platformBrightness, platformData.platformBrightness); expect(data.padding, EdgeInsets.fromViewPadding(tester.view.padding, tester.view.devicePixelRatio)); expect(data.viewPadding, EdgeInsets.fromViewPadding(tester.view.viewPadding, tester.view.devicePixelRatio)); @@ -211,7 +211,7 @@ void main() { expect(data.hashCode, data.copyWith().hashCode); expect(data.size, tester.view.physicalSize / tester.view.devicePixelRatio); expect(data.devicePixelRatio, tester.view.devicePixelRatio); - expect(data.textScaleFactor, tester.platformDispatcher.textScaleFactor); + expect(data.textScaler, TextScaler.linear(tester.platformDispatcher.textScaleFactor)); expect(data.platformBrightness, tester.platformDispatcher.platformBrightness); expect(data.padding, EdgeInsets.fromViewPadding(tester.view.padding, tester.view.devicePixelRatio)); expect(data.viewPadding, EdgeInsets.fromViewPadding(tester.view.viewPadding, tester.view.devicePixelRatio)); @@ -260,7 +260,7 @@ void main() { expect(data, isNot(platformData)); expect(data.size, tester.view.physicalSize / tester.view.devicePixelRatio); expect(data.devicePixelRatio, tester.view.devicePixelRatio); - expect(data.textScaleFactor, platformData.textScaleFactor); + expect(data.textScaler, TextScaler.linear(platformData.textScaleFactor)); expect(data.platformBrightness, platformData.platformBrightness); expect(data.padding, EdgeInsets.fromViewPadding(tester.view.padding, tester.view.devicePixelRatio)); expect(data.viewPadding, EdgeInsets.fromViewPadding(tester.view.viewPadding, tester.view.devicePixelRatio)); @@ -311,7 +311,7 @@ void main() { expect(outerData, isNull); expect(data.size, tester.view.physicalSize / tester.view.devicePixelRatio); expect(data.devicePixelRatio, tester.view.devicePixelRatio); - expect(data.textScaleFactor, tester.platformDispatcher.textScaleFactor); + expect(data.textScaler, TextScaler.linear(tester.platformDispatcher.textScaleFactor)); expect(data.platformBrightness, tester.platformDispatcher.platformBrightness); expect(data.padding, EdgeInsets.fromViewPadding(tester.view.padding, tester.view.devicePixelRatio)); expect(data.viewPadding, EdgeInsets.fromViewPadding(tester.view.viewPadding, tester.view.devicePixelRatio)); @@ -367,10 +367,10 @@ void main() { expect(outerData, isNull); expect(rebuildCount, 1); - expect(data.textScaleFactor, 123); + expect(data.textScaler, const TextScaler.linear(123)); tester.platformDispatcher.textScaleFactorTestValue = 456; await tester.pump(); - expect(data.textScaleFactor, 456); + expect(data.textScaler, const TextScaler.linear(456)); expect(rebuildCount, 2); expect(data.platformBrightness, Brightness.dark); @@ -407,7 +407,7 @@ void main() { await tester.pumpWidget( MediaQuery( data: const MediaQueryData( - textScaleFactor: 44, + textScaler: TextScaler.linear(44), platformBrightness: Brightness.dark, accessibleNavigation: true, ), @@ -426,10 +426,10 @@ void main() { expect(rebuildCount, 1); - expect(data.textScaleFactor, 44); + expect(data.textScaler, const TextScaler.linear(44)); tester.platformDispatcher.textScaleFactorTestValue = 456; await tester.pump(); - expect(data.textScaleFactor, 44); + expect(data.textScaler, const TextScaler.linear(44)); expect(rebuildCount, 1); expect(data.platformBrightness, Brightness.dark); @@ -454,14 +454,14 @@ void main() { testWidgets('MediaQuery.fromView updates when parent data changes', (WidgetTester tester) async { late MediaQueryData data; int rebuildCount = 0; - double textScaleFactor = 55; + TextScaler textScaler = const TextScaler.linear(55); late StateSetter stateSetter; await tester.pumpWidget( StatefulBuilder( builder: (BuildContext context, StateSetter setState) { stateSetter = setState; return MediaQuery( - data: MediaQueryData(textScaleFactor: textScaleFactor), + data: MediaQueryData(textScaler: textScaler), child: MediaQuery.fromView( view: tester.view, child: Builder( @@ -478,13 +478,13 @@ void main() { ); expect(rebuildCount, 1); - expect(data.textScaleFactor, 55); + expect(data.textScaler, const TextScaler.linear(55)); stateSetter(() { - textScaleFactor = 66; + textScaler = const TextScaler.linear(66); }); await tester.pump(); - expect(data.textScaleFactor, 66); + expect(data.textScaler, const TextScaler.linear(66)); expect(rebuildCount, 2); }); @@ -493,7 +493,7 @@ void main() { final MediaQueryData copied = data.copyWith(); expect(copied.size, data.size); expect(copied.devicePixelRatio, data.devicePixelRatio); - expect(copied.textScaleFactor, data.textScaleFactor); + expect(copied.textScaler, data.textScaler); expect(copied.padding, data.padding); expect(copied.viewPadding, data.viewPadding); expect(copied.viewInsets, data.viewInsets); @@ -515,7 +515,7 @@ void main() { // values are copied over exactly const Size customSize = Size(3.14, 2.72); const double customDevicePixelRatio = 1.41; - const double customTextScaleFactor = 1.62; + const TextScaler customTextScaler = TextScaler.linear(1.23); const EdgeInsets customPadding = EdgeInsets.all(9.10938); const EdgeInsets customViewPadding = EdgeInsets.all(11.24031); const EdgeInsets customViewInsets = EdgeInsets.all(1.67262); @@ -533,7 +533,7 @@ void main() { final MediaQueryData copied = data.copyWith( size: customSize, devicePixelRatio: customDevicePixelRatio, - textScaleFactor: customTextScaleFactor, + textScaler: customTextScaler, padding: customPadding, viewPadding: customViewPadding, viewInsets: customViewInsets, @@ -552,7 +552,7 @@ void main() { ); expect(copied.size, customSize); expect(copied.devicePixelRatio, customDevicePixelRatio); - expect(copied.textScaleFactor, customTextScaleFactor); + expect(copied.textScaler, customTextScaler); expect(copied.padding, customPadding); expect(copied.viewPadding, customViewPadding); expect(copied.viewInsets, customViewInsets); @@ -573,7 +573,7 @@ void main() { testWidgets('MediaQuery.removePadding removes specified padding', (WidgetTester tester) async { const Size size = Size(2.0, 4.0); const double devicePixelRatio = 2.0; - const double textScaleFactor = 1.2; + const TextScaler textScaler = TextScaler.linear(1.2); const EdgeInsets padding = EdgeInsets.only(top: 1.0, right: 2.0, left: 3.0, bottom: 4.0); const EdgeInsets viewPadding = EdgeInsets.only(top: 6.0, right: 8.0, left: 10.0, bottom: 12.0); const EdgeInsets viewInsets = EdgeInsets.only(top: 5.0, right: 6.0, left: 7.0, bottom: 8.0); @@ -591,7 +591,7 @@ void main() { data: const MediaQueryData( size: size, devicePixelRatio: devicePixelRatio, - textScaleFactor: textScaleFactor, + textScaler: textScaler, padding: padding, viewPadding: viewPadding, viewInsets: viewInsets, @@ -627,7 +627,7 @@ void main() { expect(unpadded.size, size); expect(unpadded.devicePixelRatio, devicePixelRatio); - expect(unpadded.textScaleFactor, textScaleFactor); + expect(unpadded.textScaler, textScaler); expect(unpadded.padding, EdgeInsets.zero); expect(unpadded.viewPadding, viewInsets); expect(unpadded.viewInsets, viewInsets); @@ -645,7 +645,7 @@ void main() { testWidgets('MediaQuery.removePadding only removes specified padding', (WidgetTester tester) async { const Size size = Size(2.0, 4.0); const double devicePixelRatio = 2.0; - const double textScaleFactor = 1.2; + const TextScaler textScaler = TextScaler.linear(1.2); const EdgeInsets padding = EdgeInsets.only(top: 1.0, right: 2.0, left: 3.0, bottom: 4.0); const EdgeInsets viewPadding = EdgeInsets.only(top: 6.0, right: 8.0, left: 10.0, bottom: 12.0); const EdgeInsets viewInsets = EdgeInsets.only(top: 5.0, right: 6.0, left: 7.0, bottom: 8.0); @@ -663,7 +663,7 @@ void main() { data: const MediaQueryData( size: size, devicePixelRatio: devicePixelRatio, - textScaleFactor: textScaleFactor, + textScaler: textScaler, padding: padding, viewPadding: viewPadding, viewInsets: viewInsets, @@ -696,7 +696,7 @@ void main() { expect(unpadded.size, size); expect(unpadded.devicePixelRatio, devicePixelRatio); - expect(unpadded.textScaleFactor, textScaleFactor); + expect(unpadded.textScaler, textScaler); expect(unpadded.padding, padding.copyWith(top: 0)); expect(unpadded.viewPadding, viewPadding.copyWith(top: viewInsets.top)); expect(unpadded.viewInsets, viewInsets); @@ -714,7 +714,7 @@ void main() { testWidgets('MediaQuery.removeViewInsets removes specified viewInsets', (WidgetTester tester) async { const Size size = Size(2.0, 4.0); const double devicePixelRatio = 2.0; - const double textScaleFactor = 1.2; + const TextScaler textScaler = TextScaler.linear(1.2); const EdgeInsets padding = EdgeInsets.only(top: 5.0, right: 6.0, left: 7.0, bottom: 8.0); const EdgeInsets viewPadding = EdgeInsets.only(top: 6.0, right: 8.0, left: 10.0, bottom: 12.0); const EdgeInsets viewInsets = EdgeInsets.only(top: 1.0, right: 2.0, left: 3.0, bottom: 4.0); @@ -732,7 +732,7 @@ void main() { data: const MediaQueryData( size: size, devicePixelRatio: devicePixelRatio, - textScaleFactor: textScaleFactor, + textScaler: textScaler, padding: padding, viewPadding: viewPadding, viewInsets: viewInsets, @@ -768,7 +768,7 @@ void main() { expect(unpadded.size, size); expect(unpadded.devicePixelRatio, devicePixelRatio); - expect(unpadded.textScaleFactor, textScaleFactor); + expect(unpadded.textScaler, textScaler); expect(unpadded.padding, padding); expect(unpadded.viewPadding, padding); expect(unpadded.viewInsets, EdgeInsets.zero); @@ -786,7 +786,7 @@ void main() { testWidgets('MediaQuery.removeViewInsets removes only specified viewInsets', (WidgetTester tester) async { const Size size = Size(2.0, 4.0); const double devicePixelRatio = 2.0; - const double textScaleFactor = 1.2; + const TextScaler textScaler = TextScaler.linear(1.2); const EdgeInsets padding = EdgeInsets.only(top: 5.0, right: 6.0, left: 7.0, bottom: 8.0); const EdgeInsets viewPadding = EdgeInsets.only(top: 6.0, right: 8.0, left: 10.0, bottom: 12.0); const EdgeInsets viewInsets = EdgeInsets.only(top: 1.0, right: 2.0, left: 3.0, bottom: 4.0); @@ -804,7 +804,7 @@ void main() { data: const MediaQueryData( size: size, devicePixelRatio: devicePixelRatio, - textScaleFactor: textScaleFactor, + textScaler: textScaler, padding: padding, viewPadding: viewPadding, viewInsets: viewInsets, @@ -837,7 +837,7 @@ void main() { expect(unpadded.size, size); expect(unpadded.devicePixelRatio, devicePixelRatio); - expect(unpadded.textScaleFactor, textScaleFactor); + expect(unpadded.textScaler, textScaler); expect(unpadded.padding, padding); expect(unpadded.viewPadding, viewPadding.copyWith(bottom: 8)); expect(unpadded.viewInsets, viewInsets.copyWith(bottom: 0)); @@ -855,7 +855,7 @@ void main() { testWidgets('MediaQuery.removeViewPadding removes specified viewPadding', (WidgetTester tester) async { const Size size = Size(2.0, 4.0); const double devicePixelRatio = 2.0; - const double textScaleFactor = 1.2; + const TextScaler textScaler = TextScaler.linear(1.2); const EdgeInsets padding = EdgeInsets.only(top: 5.0, right: 6.0, left: 7.0, bottom: 8.0); const EdgeInsets viewPadding = EdgeInsets.only(top: 6.0, right: 8.0, left: 10.0, bottom: 12.0); const EdgeInsets viewInsets = EdgeInsets.only(top: 1.0, right: 2.0, left: 3.0, bottom: 4.0); @@ -873,7 +873,7 @@ void main() { data: const MediaQueryData( size: size, devicePixelRatio: devicePixelRatio, - textScaleFactor: textScaleFactor, + textScaler: textScaler, padding: padding, viewPadding: viewPadding, viewInsets: viewInsets, @@ -909,7 +909,7 @@ void main() { expect(unpadded.size, size); expect(unpadded.devicePixelRatio, devicePixelRatio); - expect(unpadded.textScaleFactor, textScaleFactor); + expect(unpadded.textScaler, textScaler); expect(unpadded.padding, EdgeInsets.zero); expect(unpadded.viewPadding, EdgeInsets.zero); expect(unpadded.viewInsets, viewInsets); @@ -927,7 +927,7 @@ void main() { testWidgets('MediaQuery.removeViewPadding removes only specified viewPadding', (WidgetTester tester) async { const Size size = Size(2.0, 4.0); const double devicePixelRatio = 2.0; - const double textScaleFactor = 1.2; + const TextScaler textScaler = TextScaler.linear(1.2); const EdgeInsets padding = EdgeInsets.only(top: 5.0, right: 6.0, left: 7.0, bottom: 8.0); const EdgeInsets viewPadding = EdgeInsets.only(top: 6.0, right: 8.0, left: 10.0, bottom: 12.0); const EdgeInsets viewInsets = EdgeInsets.only(top: 1.0, right: 2.0, left: 3.0, bottom: 4.0); @@ -945,7 +945,7 @@ void main() { data: const MediaQueryData( size: size, devicePixelRatio: devicePixelRatio, - textScaleFactor: textScaleFactor, + textScaler: textScaler, padding: padding, viewPadding: viewPadding, viewInsets: viewInsets, @@ -978,7 +978,7 @@ void main() { expect(unpadded.size, size); expect(unpadded.devicePixelRatio, devicePixelRatio); - expect(unpadded.textScaleFactor, textScaleFactor); + expect(unpadded.textScaler, textScaler); expect(unpadded.padding, padding.copyWith(left: 0)); expect(unpadded.viewPadding, viewPadding.copyWith(left: 0)); expect(unpadded.viewInsets, viewInsets); @@ -993,21 +993,21 @@ void main() { expect(unpadded.displayFeatures, displayFeatures); }); - testWidgets('MediaQuery.textScaleFactorOf', (WidgetTester tester) async { - late double outsideTextScaleFactor; - late double insideTextScaleFactor; + testWidgets('MediaQuery.textScalerOf', (WidgetTester tester) async { + late TextScaler outsideTextScaler; + late TextScaler insideTextScaler; await tester.pumpWidget( Builder( builder: (BuildContext context) { - outsideTextScaleFactor = MediaQuery.textScaleFactorOf(context); + outsideTextScaler = MediaQuery.textScalerOf(context); return MediaQuery( data: const MediaQueryData( - textScaleFactor: 4.0, + textScaler: TextScaler.linear(4.0), ), child: Builder( builder: (BuildContext context) { - insideTextScaleFactor = MediaQuery.textScaleFactorOf(context); + insideTextScaler = MediaQuery.textScalerOf(context); return Container(); }, ), @@ -1016,8 +1016,8 @@ void main() { ), ); - expect(outsideTextScaleFactor, 1.0); - expect(insideTextScaleFactor, 4.0); + expect(outsideTextScaler, TextScaler.noScaling); + expect(insideTextScaler, const TextScaler.linear(4.0)); }); testWidgets('MediaQuery.platformBrightnessOf', (WidgetTester tester) async { @@ -1192,7 +1192,7 @@ void main() { testWidgets('MediaQuery.removeDisplayFeatures removes specified display features and padding', (WidgetTester tester) async { const Size size = Size(82.0, 40.0); const double devicePixelRatio = 2.0; - const double textScaleFactor = 1.2; + const TextScaler textScaler = TextScaler.linear(1.2); const EdgeInsets padding = EdgeInsets.only(top: 1.0, right: 2.0, left: 3.0, bottom: 4.0); const EdgeInsets viewPadding = EdgeInsets.only(top: 6.0, right: 8.0, left: 10.0, bottom: 12.0); const EdgeInsets viewInsets = EdgeInsets.only(top: 5.0, right: 6.0, left: 7.0, bottom: 8.0); @@ -1218,7 +1218,7 @@ void main() { data: const MediaQueryData( size: size, devicePixelRatio: devicePixelRatio, - textScaleFactor: textScaleFactor, + textScaler: textScaler, padding: padding, viewPadding: viewPadding, viewInsets: viewInsets, @@ -1249,7 +1249,7 @@ void main() { expect(subScreenMediaQuery.size, size); expect(subScreenMediaQuery.devicePixelRatio, devicePixelRatio); - expect(subScreenMediaQuery.textScaleFactor, textScaleFactor); + expect(subScreenMediaQuery.textScaler, textScaler); expect(subScreenMediaQuery.padding, EdgeInsets.zero); expect(subScreenMediaQuery.viewPadding, EdgeInsets.zero); expect(subScreenMediaQuery.viewInsets, EdgeInsets.zero); @@ -1266,7 +1266,7 @@ void main() { testWidgets('MediaQuery.removePadding only removes specified display features and padding', (WidgetTester tester) async { const Size size = Size(82.0, 40.0); const double devicePixelRatio = 2.0; - const double textScaleFactor = 1.2; + const TextScaler textScaler = TextScaler.linear(1.2); const EdgeInsets padding = EdgeInsets.only(top: 1.0, right: 2.0, left: 3.0, bottom: 4.0); const EdgeInsets viewPadding = EdgeInsets.only(top: 6.0, right: 8.0, left: 46.0, bottom: 12.0); const EdgeInsets viewInsets = EdgeInsets.only(top: 5.0, right: 6.0, left: 7.0, bottom: 8.0); @@ -1293,7 +1293,7 @@ void main() { data: const MediaQueryData( size: size, devicePixelRatio: devicePixelRatio, - textScaleFactor: textScaleFactor, + textScaler: textScaler, padding: padding, viewPadding: viewPadding, viewInsets: viewInsets, @@ -1324,7 +1324,7 @@ void main() { expect(subScreenMediaQuery.size, size); expect(subScreenMediaQuery.devicePixelRatio, devicePixelRatio); - expect(subScreenMediaQuery.textScaleFactor, textScaleFactor); + expect(subScreenMediaQuery.textScaler, textScaler); expect( subScreenMediaQuery.padding, const EdgeInsets.only(top: 1.0, right: 2.0, bottom: 4.0), @@ -1357,11 +1357,11 @@ void main() { testWidgets('MediaQuery can be partially depended-on', (WidgetTester tester) async { MediaQueryData data = const MediaQueryData( size: Size(800, 600), - textScaleFactor: 1.1 + textScaler: TextScaler.linear(1.1), ); int sizeBuildCount = 0; - int textScaleFactorBuildCount = 0; + int textScalerBuildCount = 0; final Widget showSize = Builder( builder: (BuildContext context) { @@ -1370,10 +1370,10 @@ void main() { } ); - final Widget showTextScaleFactor = Builder( + final Widget showTextScaler = Builder( builder: (BuildContext context) { - textScaleFactorBuildCount++; - return Text('textScaleFactor: ${MediaQuery.textScaleFactorOf(context).toStringAsFixed(1)}'); + textScalerBuildCount++; + return Text('textScaler: ${MediaQuery.textScalerOf(context)}'); } ); @@ -1385,7 +1385,7 @@ void main() { child: Column( children: [ showSize, - showTextScaleFactor, + showTextScaler, ElevatedButton( onPressed: () { setState(() { @@ -1397,10 +1397,10 @@ void main() { ElevatedButton( onPressed: () { setState(() { - data = data.copyWith(textScaleFactor: data.textScaleFactor + 0.1); + data = data.copyWith(textScaler: TextScaler.noScaling); }); }, - child: const Text('Increase textScaleFactor by 0.1') + child: const Text('Disable text scaling') ) ] ) @@ -1411,23 +1411,23 @@ void main() { await tester.pumpWidget(MaterialApp(home: page)); expect(find.text('size: Size(800.0, 600.0)'), findsOneWidget); - expect(find.text('textScaleFactor: 1.1'), findsOneWidget); + expect(find.text('textScaler: linear (1.1x)'), findsOneWidget); expect(sizeBuildCount, 1); - expect(textScaleFactorBuildCount, 1); + expect(textScalerBuildCount, 1); await tester.tap(find.text('Increase width by 100')); await tester.pumpAndSettle(); expect(find.text('size: Size(900.0, 600.0)'), findsOneWidget); - expect(find.text('textScaleFactor: 1.1'), findsOneWidget); + expect(find.text('textScaler: linear (1.1x)'), findsOneWidget); expect(sizeBuildCount, 2); - expect(textScaleFactorBuildCount, 1); + expect(textScalerBuildCount, 1); - await tester.tap(find.text('Increase textScaleFactor by 0.1')); + await tester.tap(find.text('Disable text scaling')); await tester.pumpAndSettle(); expect(find.text('size: Size(900.0, 600.0)'), findsOneWidget); - expect(find.text('textScaleFactor: 1.2'), findsOneWidget); + expect(find.text('textScaler: no scaling'), findsOneWidget); expect(sizeBuildCount, 2); - expect(textScaleFactorBuildCount, 2); + expect(textScalerBuildCount, 2); }); testWidgets('MediaQuery partial dependencies', (WidgetTester tester) async { @@ -1496,6 +1496,8 @@ void main() { const _MediaQueryAspectCase(MediaQuery.maybeDevicePixelRatioOf, MediaQueryData(devicePixelRatio: 1.1)), const _MediaQueryAspectCase(MediaQuery.textScaleFactorOf, MediaQueryData(textScaleFactor: 1.1)), const _MediaQueryAspectCase(MediaQuery.maybeTextScaleFactorOf, MediaQueryData(textScaleFactor: 1.1)), + const _MediaQueryAspectCase(MediaQuery.textScalerOf, MediaQueryData(textScaler: TextScaler.linear(1.1))), + const _MediaQueryAspectCase(MediaQuery.maybeTextScalerOf, MediaQueryData(textScaler: TextScaler.linear(1.1))), const _MediaQueryAspectCase(MediaQuery.platformBrightnessOf, MediaQueryData(platformBrightness: Brightness.dark)), const _MediaQueryAspectCase(MediaQuery.maybePlatformBrightnessOf, MediaQueryData(platformBrightness: Brightness.dark)), const _MediaQueryAspectCase(MediaQuery.paddingOf, MediaQueryData(padding: EdgeInsets.all(1))), diff --git a/packages/flutter/test/widgets/rich_text_test.dart b/packages/flutter/test/widgets/rich_text_test.dart index e8c83eea5b..474854c22e 100644 --- a/packages/flutter/test/widgets/rich_text_test.dart +++ b/packages/flutter/test/widgets/rich_text_test.dart @@ -193,12 +193,12 @@ void main() { .map((DiagnosticsNode node) => node.toString()) .toList(); - expect(description, unorderedMatches([ + expect(description, unorderedMatches([ contains('textAlign: center'), contains('textDirection: rtl'), contains('softWrap: no wrapping except at line break characters'), contains('overflow: ellipsis'), - contains('textScaleFactor: 1.3'), + contains('textScaler: linear (1.3x)'), contains('maxLines: 1'), contains('textWidthBasis: longestLine'), contains('text: "rich text"'), diff --git a/packages/flutter/test/widgets/selectable_text_test.dart b/packages/flutter/test/widgets/selectable_text_test.dart index 34099ff2e0..033d5c2f45 100644 --- a/packages/flutter/test/widgets/selectable_text_test.dart +++ b/packages/flutter/test/widgets/selectable_text_test.dart @@ -4094,7 +4094,7 @@ void main() { style: TextStyle(color: Color(0xff00ff00)), textAlign: TextAlign.end, textDirection: TextDirection.ltr, - textScaleFactor: 1.0, + textScaler: TextScaler.noScaling, autofocus: true, showCursor: true, minLines: 2, @@ -4122,7 +4122,7 @@ void main() { 'maxLines: 10', 'textAlign: end', 'textDirection: ltr', - 'textScaleFactor: 1.0', + 'textScaler: no scaling', 'cursorWidth: 1.0', 'cursorHeight: 1.0', 'cursorRadius: Radius.circular(0.0)', diff --git a/packages/flutter/test/widgets/text_scaler_backward_compatibility_test.dart b/packages/flutter/test/widgets/text_scaler_backward_compatibility_test.dart new file mode 100644 index 0000000000..c38c3f617f --- /dev/null +++ b/packages/flutter/test/widgets/text_scaler_backward_compatibility_test.dart @@ -0,0 +1,278 @@ +// 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. + +// TODO(LongCatIsLooong): Remove this file once textScaleFactor is removed. +import 'package:flutter/foundation.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('TextStyle', () { + test('getTextSyle is backward compatible', () { + expect( + const TextStyle(fontSize: 14).getTextStyle(textScaleFactor: 2.0).toString(), + contains('fontSize: 28'), + ); + }, skip: kIsWeb); // [intended] CkTextStyle doesn't have a custom toString implementation. + }); + group('TextPainter', () { + test('textScaleFactor translates to textScaler', () { + final TextPainter textPainter = TextPainter( + text: const TextSpan(text: 'text'), + textDirection: TextDirection.ltr, + textScaleFactor: 42, + ); + + expect(textPainter.textScaler, const TextScaler.linear(42.0)); + + // Linear TextScaler translates to textScaleFactor. + textPainter.textScaler = const TextScaler.linear(12.0); + expect(textPainter.textScaleFactor, 12.0); + + textPainter.textScaleFactor = 10; + expect(textPainter.textScaler, const TextScaler.linear(10)); + }); + }); + + group('MediaQuery', () { + test('specifying both textScaler and textScalingFactor asserts', () { + expect( + () => MediaQueryData(textScaleFactor: 2, textScaler: const TextScaler.linear(2.0)), + throwsAssertionError, + ); + }); + + test('copyWith is backward compatible', () { + const MediaQueryData data = MediaQueryData(textScaler: TextScaler.linear(2.0)); + + final MediaQueryData data1 = data.copyWith(textScaleFactor: 42); + expect(data1.textScaler, const TextScaler.linear(42)); + expect(data1.textScaleFactor, 42); + + final MediaQueryData data2 = data.copyWith(textScaler: TextScaler.noScaling); + expect(data2.textScaler, TextScaler.noScaling); + expect(data2.textScaleFactor, 1.0); + }); + + test('copyWith specifying both textScaler and textScalingFactor asserts', () { + const MediaQueryData data = MediaQueryData(); + expect( + () => data.copyWith(textScaleFactor: 2, textScaler: const TextScaler.linear(2.0)), + throwsAssertionError, + ); + }); + + testWidgets('MediaQuery.textScaleFactorOf overriding compatibility', (WidgetTester tester) async { + late final double outsideTextScaleFactor; + late final TextScaler outsideTextScaler; + late final double insideTextScaleFactor; + late final TextScaler insideTextScaler; + + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + outsideTextScaleFactor = MediaQuery.textScaleFactorOf(context); + outsideTextScaler = MediaQuery.textScalerOf(context); + return MediaQuery( + data: const MediaQueryData( + textScaleFactor: 4.0, + ), + child: Builder( + builder: (BuildContext context) { + insideTextScaleFactor = MediaQuery.textScaleFactorOf(context); + insideTextScaler = MediaQuery.textScalerOf(context); + return Container(); + }, + ), + ); + }, + ), + ); + + // Overriding textScaleFactor should work for unmigrated widgets that are + // still using MediaQuery.textScaleFactorOf. Also if a unmigrated widget + // overrides MediaQuery.textScaleFactor, migrated widgets in the subtree + // should get the correct TextScaler. + expect(outsideTextScaleFactor, 1.0); + expect(outsideTextScaler.textScaleFactor, 1.0); + expect(outsideTextScaler, TextScaler.noScaling); + expect(insideTextScaleFactor, 4.0); + expect(insideTextScaler.textScaleFactor, 4.0); + expect(insideTextScaler, const TextScaler.linear(4.0)); + }); + + testWidgets('textScaleFactor overriding backward compatibility', (WidgetTester tester) async { + late final double outsideTextScaleFactor; + late final TextScaler outsideTextScaler; + late final double insideTextScaleFactor; + late final TextScaler insideTextScaler; + + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + outsideTextScaleFactor = MediaQuery.textScaleFactorOf(context); + outsideTextScaler = MediaQuery.textScalerOf(context); + return MediaQuery( + data: const MediaQueryData(textScaler: TextScaler.linear(4.0)), + child: Builder( + builder: (BuildContext context) { + insideTextScaleFactor = MediaQuery.textScaleFactorOf(context); + insideTextScaler = MediaQuery.textScalerOf(context); + return Container(); + }, + ), + ); + }, + ), + ); + + expect(outsideTextScaleFactor, 1.0); + expect(outsideTextScaler.textScaleFactor, 1.0); + expect(outsideTextScaler, TextScaler.noScaling); + expect(insideTextScaleFactor, 4.0); + expect(insideTextScaler.textScaleFactor, 4.0); + expect(insideTextScaler, const TextScaler.linear(4.0)); + }); + }); + + group('RenderObjects backward compatibility', () { + test('RenderEditable', () { + final RenderEditable renderObject = RenderEditable( + backgroundCursorColor: const Color.fromARGB(0xFF, 0xFF, 0x00, 0x00), + textDirection: TextDirection.ltr, + cursorColor: const Color.fromARGB(0xFF, 0xFF, 0x00, 0x00), + offset: ViewportOffset.zero(), + textSelectionDelegate: _FakeEditableTextState(), + text: const TextSpan( + text: 'test', + style: TextStyle(height: 1.0, fontSize: 10.0), + ), + startHandleLayerLink: LayerLink(), + endHandleLayerLink: LayerLink(), + selection: const TextSelection.collapsed(offset: 0), + ); + expect(renderObject.textScaleFactor, 1.0); + + renderObject.textScaleFactor = 3.0; + expect(renderObject.textScaleFactor, 3.0); + expect(renderObject.textScaler, const TextScaler.linear(3.0)); + + renderObject.textScaler = const TextScaler.linear(4.0); + expect(renderObject.textScaleFactor, 4.0); + }); + + test('RenderParagraph', () { + final RenderParagraph renderObject = RenderParagraph( + const TextSpan( + text: 'test', + style: TextStyle(height: 1.0, fontSize: 10.0), + ), + textDirection: TextDirection.ltr, + ); + expect(renderObject.textScaleFactor, 1.0); + + renderObject.textScaleFactor = 3.0; + expect(renderObject.textScaleFactor, 3.0); + expect(renderObject.textScaler, const TextScaler.linear(3.0)); + + renderObject.textScaler = const TextScaler.linear(4.0); + expect(renderObject.textScaleFactor, 4.0); + }); + }); + + group('Widgets backward compatibility', () { + testWidgets('RichText', (WidgetTester tester) async { + await tester.pumpWidget( + RichText( + textDirection: TextDirection.ltr, + text: const TextSpan(), + textScaleFactor: 2.0, + ), + ); + + expect( + tester.renderObject(find.byType(RichText)).textScaler, + const TextScaler.linear(2.0), + ); + expect(tester.renderObject(find.byType(RichText)).textScaleFactor, 2.0); + }); + + testWidgets('Text', (WidgetTester tester) async { + await tester.pumpWidget( + const Text( + 'text', + textDirection: TextDirection.ltr, + textScaleFactor: 2.0, + ), + ); + + expect( + tester.renderObject(find.text('text')).textScaler, + const TextScaler.linear(2.0), + ); + }); + + testWidgets('EditableText', (WidgetTester tester) async { + final TextEditingController controller = TextEditingController(); + final FocusNode focusNode = FocusNode(debugLabel: 'EditableText Node'); + const TextStyle textStyle = TextStyle(); + const Color cursorColor = Color.fromARGB(0xFF, 0xFF, 0x00, 0x00); + await tester.pumpWidget( + MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.rtl, + child: EditableText( + backgroundCursorColor: cursorColor, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + textScaleFactor: 2.0, + ), + ), + ), + ); + + final RenderEditable renderEditable = tester.allRenderObjects.whereType().first; + expect( + renderEditable.textScaler, + const TextScaler.linear(2.0), + ); + }); + }); +} + +class _FakeEditableTextState with TextSelectionDelegate { + @override + TextEditingValue textEditingValue = TextEditingValue.empty; + + TextSelection? selection; + + @override + void hideToolbar([bool hideHandles = true]) { } + + @override + void userUpdateTextEditingValue(TextEditingValue value, SelectionChangedCause cause) { + selection = value.selection; + } + + @override + void bringIntoView(TextPosition position) { } + + @override + void cutSelection(SelectionChangedCause cause) { } + + @override + Future pasteText(SelectionChangedCause cause) { + return Future.value(); + } + + @override + void selectAll(SelectionChangedCause cause) { } + + @override + void copySelection(SelectionChangedCause cause) { } +} diff --git a/packages/flutter/test/widgets/text_test.dart b/packages/flutter/test/widgets/text_test.dart index 0289a64d20..c535fbd9c5 100644 --- a/packages/flutter/test/widgets/text_test.dart +++ b/packages/flutter/test/widgets/text_test.dart @@ -24,7 +24,7 @@ void main() { RichText text = tester.firstWidget(find.byType(RichText)); expect(text, isNotNull); - expect(text.textScaleFactor, 1.3); + expect(text.textScaler, const TextScaler.linear(1.3)); await tester.pumpWidget(const Center( child: Text('Hello', textDirection: TextDirection.ltr), @@ -32,7 +32,7 @@ void main() { text = tester.firstWidget(find.byType(RichText)); expect(text, isNotNull); - expect(text.textScaleFactor, 1.0); + expect(text.textScaler, TextScaler.noScaling); }); testWidgets('Text respects textScaleFactor with default font size', (WidgetTester tester) async { @@ -42,7 +42,7 @@ void main() { RichText text = tester.firstWidget(find.byType(RichText)); expect(text, isNotNull); - expect(text.textScaleFactor, 1.0); + expect(text.textScaler, TextScaler.noScaling); final Size baseSize = tester.getSize(find.byType(RichText)); expect(baseSize.width, equals(70.0)); expect(baseSize.height, equals(14.0)); @@ -57,7 +57,7 @@ void main() { text = tester.firstWidget(find.byType(RichText)); expect(text, isNotNull); - expect(text.textScaleFactor, 1.5); + expect(text.textScaler, const TextScaler.linear(1.5)); final Size largeSize = tester.getSize(find.byType(RichText)); expect(largeSize.width, 105.0); expect(largeSize.height, equals(21.0)); @@ -74,7 +74,7 @@ void main() { RichText text = tester.firstWidget(find.byType(RichText)); expect(text, isNotNull); - expect(text.textScaleFactor, 1.0); + expect(text.textScaler, TextScaler.noScaling); final Size baseSize = tester.getSize(find.byType(RichText)); expect(baseSize.width, equals(100.0)); expect(baseSize.height, equals(20.0)); @@ -90,7 +90,7 @@ void main() { text = tester.firstWidget(find.byType(RichText)); expect(text, isNotNull); - expect(text.textScaleFactor, 1.3); + expect(text.textScaler, const TextScaler.linear(1.3)); final Size largeSize = tester.getSize(find.byType(RichText)); expect(largeSize.width, 130.0); expect(largeSize.height, equals(26.0)); diff --git a/packages/flutter/test/widgets/widget_span_test.dart b/packages/flutter/test/widgets/widget_span_test.dart new file mode 100644 index 0000000000..d903ab567e --- /dev/null +++ b/packages/flutter/test/widgets/widget_span_test.dart @@ -0,0 +1,77 @@ +// 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:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + test('WidgetSpan codeUnitAt', () { + const InlineSpan span = WidgetSpan(child: SizedBox()); + expect(span.codeUnitAt(-1), isNull); + expect(span.codeUnitAt(0), PlaceholderSpan.placeholderCodeUnit); + expect(span.codeUnitAt(1), isNull); + expect(span.codeUnitAt(2), isNull); + + const InlineSpan nestedSpan = TextSpan( + text: 'AAA', + children: [span, span], + ); + expect(nestedSpan.codeUnitAt(-1), isNull); + expect(nestedSpan.codeUnitAt(0), 65); + expect(nestedSpan.codeUnitAt(1), 65); + expect(nestedSpan.codeUnitAt(2), 65); + expect(nestedSpan.codeUnitAt(3), PlaceholderSpan.placeholderCodeUnit); + expect(nestedSpan.codeUnitAt(4), PlaceholderSpan.placeholderCodeUnit); + expect(nestedSpan.codeUnitAt(5), isNull); + }); + + test('WidgetSpan.extractFromInlineSpan applies the correct scaling factor', () { + const WidgetSpan a = WidgetSpan(child: SizedBox(), style: TextStyle(fontSize: 0)); + const WidgetSpan b = WidgetSpan(child: SizedBox(), style: TextStyle(fontSize: 10)); + const WidgetSpan c = WidgetSpan(child: SizedBox()); + const WidgetSpan d = WidgetSpan(child: SizedBox(), style: TextStyle(letterSpacing: 999)); + + const TextSpan span = TextSpan( + children: [ + a, // fontSize = 0. + TextSpan( + children: [ + b, // fontSize = 10. + c, // fontSize = 20. + ], + style: TextStyle(fontSize: 20), + ), + d, // fontSize = 14. + ] + ); + + double effectiveTextScaleFactorFromWidget(Widget widget) { + final Semantics child = (widget as ProxyWidget).child as Semantics; + final dynamic grandChild = child.child; + final double textScaleFactor = grandChild.textScaleFactor as double; // ignore: avoid_dynamic_calls + return textScaleFactor; + } + + final List textScaleFactors = WidgetSpan.extractFromInlineSpan(span, const _QuadraticScaler()) + .map(effectiveTextScaleFactorFromWidget).toList(); + + expect(textScaleFactors, [ + 0, // a + 10, // b + 20, // c + 14, // d + ]); + }); +} + + +class _QuadraticScaler extends TextScaler { + const _QuadraticScaler(); + + @override + double scale(double fontSize) => fontSize * fontSize; + + @override + double get textScaleFactor => throw UnimplementedError(); +} diff --git a/packages/flutter/test_fixes/painting/painting.dart b/packages/flutter/test_fixes/painting/painting.dart index 625a0e701d..2f2669f355 100644 --- a/packages/flutter/test_fixes/painting/painting.dart +++ b/packages/flutter/test_fixes/painting/painting.dart @@ -7,4 +7,15 @@ import 'package:flutter/painting.dart'; void main() { // Change made in https://github.com/flutter/flutter/pull/121152 final EdgeInsets insets = EdgeInsets.fromWindowPadding(ViewPadding.zero, 3.0); + + // Change made in https://github.com/flutter/flutter/pull/128522 + const TextStyle textStyle = TextStyle() + ..getTextStyle(textScaleFactor: math.min(_kTextScaleFactor, 1.0)) + ..getTextStyle(); + + TextPainter(text: inlineSpan); + TextPainter(textScaleFactor: someValue); + + TextPainter.computeWidth(textScaleFactor: textScaleFactor); + TextPainter.computeMaxIntrinsicWidth(textScaleFactor: textScaleFactor); } diff --git a/packages/flutter/test_fixes/painting/painting.dart.expect b/packages/flutter/test_fixes/painting/painting.dart.expect index 245193c853..249f3dac39 100644 --- a/packages/flutter/test_fixes/painting/painting.dart.expect +++ b/packages/flutter/test_fixes/painting/painting.dart.expect @@ -7,4 +7,15 @@ import 'package:flutter/painting.dart'; void main() { // Change made in https://github.com/flutter/flutter/pull/121152 final EdgeInsets insets = EdgeInsets.fromViewPadding(ViewPadding.zero, 3.0); + + // Change made in https://github.com/flutter/flutter/pull/128522 + const TextStyle textStyle = TextStyle() + ..getTextStyle(textScaler: TextScaler.linear(math.min(_kTextScaleFactor, 1.0))) + ..getTextStyle(); + + TextPainter(text: inlineSpan); + TextPainter(textScaler: TextScaler.linear(someValue)); + + TextPainter.computeWidth(textScaler: TextScaler.linear(textScaleFactor)); + TextPainter.computeMaxIntrinsicWidth(textScaler: TextScaler.linear(textScaleFactor)); } diff --git a/packages/flutter/test_fixes/rendering/rendering.dart b/packages/flutter/test_fixes/rendering/rendering.dart index f8bfd0d1a5..705085486f 100644 --- a/packages/flutter/test_fixes/rendering/rendering.dart +++ b/packages/flutter/test_fixes/rendering/rendering.dart @@ -18,4 +18,10 @@ void main() { renderListWheelViewport = RenderListWheelViewport(clipToSize: false); renderListWheelViewport = RenderListWheelViewport(error: ''); renderListWheelViewport.clipToSize; + + // Change made in https://github.com/flutter/flutter/pull/128522 + RenderParagraph(textScaleFactor: math.min(123, 456)); + RenderParagraph(); + RenderEditable(textScaleFactor: math.min(123, 456)); + RenderEditable(); } diff --git a/packages/flutter/test_fixes/rendering/rendering.dart.expect b/packages/flutter/test_fixes/rendering/rendering.dart.expect index 850b37fdf3..e660069f3f 100644 --- a/packages/flutter/test_fixes/rendering/rendering.dart.expect +++ b/packages/flutter/test_fixes/rendering/rendering.dart.expect @@ -18,4 +18,10 @@ void main() { renderListWheelViewport = RenderListWheelViewport(clipBehavior: Clip.none); renderListWheelViewport = RenderListWheelViewport(error: ''); renderListWheelViewport.clipBehavior; + + // Change made in https://github.com/flutter/flutter/pull/128522 + RenderParagraph(textScaler: TextScaler.linear(math.min(123, 456))); + RenderParagraph(); + RenderEditable(textScaler: TextScaler.linear(math.min(123, 456))); + RenderEditable(); } diff --git a/packages/flutter/test_fixes/widgets/media_query.dart b/packages/flutter/test_fixes/widgets/media_query.dart new file mode 100644 index 0000000000..35c8450a28 --- /dev/null +++ b/packages/flutter/test_fixes/widgets/media_query.dart @@ -0,0 +1,13 @@ +// 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:flutter/widgets.dart'; + +void main() { + // Change made in https://github.com/flutter/flutter/pull/128522 + MediaQueryData(); + MediaQueryData(textScaleFactor: 2.0) + ..copyWith(textScaleFactor: 2.0) + ..copyWith(); +} diff --git a/packages/flutter/test_fixes/widgets/media_query.dart.expect b/packages/flutter/test_fixes/widgets/media_query.dart.expect new file mode 100644 index 0000000000..6e88c7793c --- /dev/null +++ b/packages/flutter/test_fixes/widgets/media_query.dart.expect @@ -0,0 +1,13 @@ +// 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:flutter/widgets.dart'; + +void main() { + // Change made in https://github.com/flutter/flutter/pull/128522 + MediaQueryData(); + MediaQueryData(textScaler: TextScaler.linear(2.0)) + ..copyWith(textScaler: TextScaler.linear(2.0)) + ..copyWith(); +} diff --git a/packages/flutter/test_fixes/widgets/rich_text.dart b/packages/flutter/test_fixes/widgets/rich_text.dart new file mode 100644 index 0000000000..8e61177e1c --- /dev/null +++ b/packages/flutter/test_fixes/widgets/rich_text.dart @@ -0,0 +1,11 @@ +// 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:flutter/widgets.dart'; + +void main() { + // Change made in https://github.com/flutter/flutter/pull/128522 + RichText(); + RichText(textScaleFactor: 2.0); +} diff --git a/packages/flutter/test_fixes/widgets/rich_text.dart.expect b/packages/flutter/test_fixes/widgets/rich_text.dart.expect new file mode 100644 index 0000000000..c517fb4a0f --- /dev/null +++ b/packages/flutter/test_fixes/widgets/rich_text.dart.expect @@ -0,0 +1,11 @@ +// 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:flutter/widgets.dart'; + +void main() { + // Change made in https://github.com/flutter/flutter/pull/128522 + RichText(); + RichText(textScaler: TextScaler.linear(2.0)); +}