diff --git a/.ci.yaml b/.ci.yaml index a367f93f3a2..35d4b2ec200 100644 --- a/.ci.yaml +++ b/.ci.yaml @@ -327,10 +327,10 @@ targets: timeout: 30 properties: target_file: analyze_legacy.yaml - channel: "3.32.8" + channel: "3.35.7" env_variables: >- { - "CHANNEL": "3.32.8" + "CHANNEL": "3.35.7" } - name: Linux analyze_legacy N-2 @@ -338,10 +338,10 @@ targets: timeout: 30 properties: target_file: analyze_legacy.yaml - channel: "3.29.3" + channel: "3.32.8" env_variables: >- { - "CHANNEL": "3.29.3" + "CHANNEL": "3.32.8" } - name: Linux_android custom_package_tests master diff --git a/.ci/targets/repo_checks.yaml b/.ci/targets/repo_checks.yaml index 75626fe69eb..eb4071651fe 100644 --- a/.ci/targets/repo_checks.yaml +++ b/.ci/targets/repo_checks.yaml @@ -28,7 +28,7 @@ tasks: script: .ci/scripts/tool_runner.sh args: - "pubspec-check" - - "--min-min-flutter-version=3.27.0" + - "--min-min-flutter-version=3.32.0" - "--allow-dependencies=script/configs/allowed_unpinned_deps.yaml" - "--allow-pinned-dependencies=script/configs/allowed_pinned_deps.yaml" always: true diff --git a/packages/animations/CHANGELOG.md b/packages/animations/CHANGELOG.md index 1b2952928e5..c4a7544dfdb 100644 --- a/packages/animations/CHANGELOG.md +++ b/packages/animations/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. + ## 2.1.0 * Updates examples to use the new RadioGroup API instead of deprecated Radio parameters. diff --git a/packages/animations/example/lib/container_transition.dart b/packages/animations/example/lib/container_transition.dart index 2c8caf09341..4f188eae2b2 100644 --- a/packages/animations/example/lib/container_transition.dart +++ b/packages/animations/example/lib/container_transition.dart @@ -84,10 +84,9 @@ class _OpenContainerTransformDemoState onPressed: (int index) { setModalState(() { setState(() { - _transitionType = - index == 0 - ? ContainerTransitionType.fade - : ContainerTransitionType.fadeThrough; + _transitionType = index == 0 + ? ContainerTransitionType.fade + : ContainerTransitionType.fadeThrough; }); }); }, diff --git a/packages/animations/example/lib/fade_scale_transition.dart b/packages/animations/example/lib/fade_scale_transition.dart index 815de52f85f..176363a47ab 100644 --- a/packages/animations/example/lib/fade_scale_transition.dart +++ b/packages/animations/example/lib/fade_scale_transition.dart @@ -21,18 +21,19 @@ class _FadeScaleTransitionDemoState extends State @override void initState() { - _controller = AnimationController( - value: 0.0, - duration: const Duration(milliseconds: 150), - reverseDuration: const Duration(milliseconds: 75), - vsync: this, - )..addStatusListener((AnimationStatus status) { - setState(() { - // setState needs to be called to trigger a rebuild because - // the 'HIDE FAB'/'SHOW FAB' button needs to be updated based - // the latest value of [_controller.status]. - }); - }); + _controller = + AnimationController( + value: 0.0, + duration: const Duration(milliseconds: 150), + reverseDuration: const Duration(milliseconds: 75), + vsync: this, + )..addStatusListener((AnimationStatus status) { + setState(() { + // setState needs to be called to trigger a rebuild because + // the 'HIDE FAB'/'SHOW FAB' button needs to be updated based + // the latest value of [_controller.status]. + }); + }); super.initState(); } @@ -99,10 +100,9 @@ class _FadeScaleTransitionDemoState extends State _controller.forward(); } }, - child: - _isAnimationRunningForwardsOrComplete - ? const Text('HIDE FAB') - : const Text('SHOW FAB'), + child: _isAnimationRunningForwardsOrComplete + ? const Text('HIDE FAB') + : const Text('SHOW FAB'), ), ], ), diff --git a/packages/animations/example/lib/fade_through_transition.dart b/packages/animations/example/lib/fade_through_transition.dart index 2bd0cbbf35d..249c9439436 100644 --- a/packages/animations/example/lib/fade_through_transition.dart +++ b/packages/animations/example/lib/fade_through_transition.dart @@ -25,17 +25,18 @@ class _FadeThroughTransitionDemoState extends State { return Scaffold( appBar: AppBar(title: const Text('Fade through')), body: PageTransitionSwitcher( - transitionBuilder: ( - Widget child, - Animation animation, - Animation secondaryAnimation, - ) { - return FadeThroughTransition( - animation: animation, - secondaryAnimation: secondaryAnimation, - child: child, - ); - }, + transitionBuilder: + ( + Widget child, + Animation animation, + Animation secondaryAnimation, + ) { + return FadeThroughTransition( + animation: animation, + secondaryAnimation: secondaryAnimation, + child: child, + ); + }, child: pageList[pageIndex], ), bottomNavigationBar: BottomNavigationBar( diff --git a/packages/animations/example/lib/shared_axis_transition.dart b/packages/animations/example/lib/shared_axis_transition.dart index af1d682506d..299f32cbaba 100644 --- a/packages/animations/example/lib/shared_axis_transition.dart +++ b/packages/animations/example/lib/shared_axis_transition.dart @@ -44,18 +44,19 @@ class _SharedAxisTransitionDemoState extends State { Expanded( child: PageTransitionSwitcher( reverse: !_isLoggedIn, - transitionBuilder: ( - Widget child, - Animation animation, - Animation secondaryAnimation, - ) { - return SharedAxisTransition( - animation: animation, - secondaryAnimation: secondaryAnimation, - transitionType: _transitionType!, - child: child, - ); - }, + transitionBuilder: + ( + Widget child, + Animation animation, + Animation secondaryAnimation, + ) { + return SharedAxisTransition( + animation: animation, + secondaryAnimation: secondaryAnimation, + transitionType: _transitionType!, + child: child, + ); + }, child: _isLoggedIn ? _CoursePage() : _SignInPage(), ), ), diff --git a/packages/animations/example/pubspec.yaml b/packages/animations/example/pubspec.yaml index 75e7e2118e4..f0511e4d6b8 100644 --- a/packages/animations/example/pubspec.yaml +++ b/packages/animations/example/pubspec.yaml @@ -6,8 +6,8 @@ publish_to: none version: 0.0.1 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: animations: diff --git a/packages/animations/lib/src/fade_scale_transition.dart b/packages/animations/lib/src/fade_scale_transition.dart index b118c8e2b44..9c525ea7f6c 100644 --- a/packages/animations/lib/src/fade_scale_transition.dart +++ b/packages/animations/lib/src/fade_scale_transition.dart @@ -137,29 +137,23 @@ class FadeScaleTransition extends StatelessWidget { Widget build(BuildContext context) { return DualTransitionBuilder( animation: animation, - forwardBuilder: ( - BuildContext context, - Animation animation, - Widget? child, - ) { - return FadeTransition( - opacity: _fadeInTransition.animate(animation), - child: ScaleTransition( - scale: _scaleInTransition.animate(animation), - child: child, - ), - ); - }, - reverseBuilder: ( - BuildContext context, - Animation animation, - Widget? child, - ) { - return FadeTransition( - opacity: _fadeOutTransition.animate(animation), - child: child, - ); - }, + forwardBuilder: + (BuildContext context, Animation animation, Widget? child) { + return FadeTransition( + opacity: _fadeInTransition.animate(animation), + child: ScaleTransition( + scale: _scaleInTransition.animate(animation), + child: child, + ), + ); + }, + reverseBuilder: + (BuildContext context, Animation animation, Widget? child) { + return FadeTransition( + opacity: _fadeOutTransition.animate(animation), + child: child, + ); + }, child: child, ); } diff --git a/packages/animations/lib/src/fade_through_transition.dart b/packages/animations/lib/src/fade_through_transition.dart index 9acc9fe722f..61a8cb59fa7 100644 --- a/packages/animations/lib/src/fade_through_transition.dart +++ b/packages/animations/lib/src/fade_through_transition.dart @@ -222,20 +222,14 @@ class _ZoomedFadeInFadeOut extends StatelessWidget { Widget build(BuildContext context) { return DualTransitionBuilder( animation: animation, - forwardBuilder: ( - BuildContext context, - Animation animation, - Widget? child, - ) { - return _ZoomedFadeIn(animation: animation, child: child); - }, - reverseBuilder: ( - BuildContext context, - Animation animation, - Widget? child, - ) { - return _FadeOut(animation: animation, child: child); - }, + forwardBuilder: + (BuildContext context, Animation animation, Widget? child) { + return _ZoomedFadeIn(animation: animation, child: child); + }, + reverseBuilder: + (BuildContext context, Animation animation, Widget? child) { + return _FadeOut(animation: animation, child: child); + }, child: child, ); } diff --git a/packages/animations/lib/src/open_container.dart b/packages/animations/lib/src/open_container.dart index d9d601a43ed..7416ab704f9 100644 --- a/packages/animations/lib/src/open_container.dart +++ b/packages/animations/lib/src/open_container.dart @@ -288,28 +288,29 @@ class OpenContainerState extends State> { Future openContainer() async { final Color middleColor = widget.middleColor ?? Theme.of(context).canvasColor; - final T? data = await Navigator.of( - context, - rootNavigator: widget.useRootNavigator, - ).push( - _OpenContainerRoute( - closedColor: widget.closedColor, - openColor: widget.openColor, - middleColor: middleColor, - closedElevation: widget.closedElevation, - openElevation: widget.openElevation, - closedShape: widget.closedShape, - openShape: widget.openShape, - closedBuilder: widget.closedBuilder, - openBuilder: widget.openBuilder, - hideableKey: _hideableKey, - closedBuilderKey: _closedBuilderKey, - transitionDuration: widget.transitionDuration, - transitionType: widget.transitionType, - useRootNavigator: widget.useRootNavigator, - routeSettings: widget.routeSettings, - ), - ); + final T? data = + await Navigator.of( + context, + rootNavigator: widget.useRootNavigator, + ).push( + _OpenContainerRoute( + closedColor: widget.closedColor, + openColor: widget.openColor, + middleColor: middleColor, + closedElevation: widget.closedElevation, + openElevation: widget.openElevation, + closedShape: widget.closedShape, + openShape: widget.openShape, + closedBuilder: widget.closedBuilder, + openBuilder: widget.openBuilder, + hideableKey: _hideableKey, + closedBuilderKey: _closedBuilderKey, + transitionDuration: widget.transitionDuration, + transitionType: widget.transitionType, + useRootNavigator: widget.useRootNavigator, + routeSettings: widget.routeSettings, + ), + ); if (widget.onClosed != null) { widget.onClosed!(data); } @@ -747,8 +748,9 @@ class _OpenContainerRoute extends ModalRoute { final Animation curvedAnimation = CurvedAnimation( parent: animation, curve: Curves.fastOutSlowIn, - reverseCurve: - _transitionWasInterrupted ? null : Curves.fastOutSlowIn.flipped, + reverseCurve: _transitionWasInterrupted + ? null + : Curves.fastOutSlowIn.flipped, ); TweenSequence? colorTween; TweenSequence? closedOpacityTween, openOpacityTween; @@ -809,23 +811,20 @@ class _OpenContainerRoute extends ModalRoute { height: _rectTween.begin!.height, child: (hideableKey.currentState?.isInTree ?? false) - ? null - : FadeTransition( - opacity: closedOpacityTween!.animate( - animation, - ), - child: Builder( - key: closedBuilderKey, - builder: (BuildContext context) { - // Use dummy "open container" callback - // since we are in the process of opening. - return closedBuilder( - context, - () {}, - ); - }, - ), + ? null + : FadeTransition( + opacity: closedOpacityTween!.animate( + animation, + ), + child: Builder( + key: closedBuilderKey, + builder: (BuildContext context) { + // Use dummy "open container" callback + // since we are in the process of opening. + return closedBuilder(context, () {}); + }, ), + ), ), ), diff --git a/packages/animations/lib/src/shared_axis_transition.dart b/packages/animations/lib/src/shared_axis_transition.dart index a199a3c457b..f361f79cd14 100644 --- a/packages/animations/lib/src/shared_axis_transition.dart +++ b/packages/animations/lib/src/shared_axis_transition.dart @@ -233,56 +233,44 @@ class SharedAxisTransition extends StatelessWidget { final Color color = fillColor ?? Theme.of(context).canvasColor; return DualTransitionBuilder( animation: animation, - forwardBuilder: ( - BuildContext context, - Animation animation, - Widget? child, - ) { - return _EnterTransition( - animation: animation, - transitionType: transitionType, - child: child, - ); - }, - reverseBuilder: ( - BuildContext context, - Animation animation, - Widget? child, - ) { - return _ExitTransition( - animation: animation, - transitionType: transitionType, - reverse: true, - fillColor: color, - child: child, - ); - }, + forwardBuilder: + (BuildContext context, Animation animation, Widget? child) { + return _EnterTransition( + animation: animation, + transitionType: transitionType, + child: child, + ); + }, + reverseBuilder: + (BuildContext context, Animation animation, Widget? child) { + return _ExitTransition( + animation: animation, + transitionType: transitionType, + reverse: true, + fillColor: color, + child: child, + ); + }, child: DualTransitionBuilder( animation: ReverseAnimation(secondaryAnimation), - forwardBuilder: ( - BuildContext context, - Animation animation, - Widget? child, - ) { - return _EnterTransition( - animation: animation, - transitionType: transitionType, - reverse: true, - child: child, - ); - }, - reverseBuilder: ( - BuildContext context, - Animation animation, - Widget? child, - ) { - return _ExitTransition( - animation: animation, - transitionType: transitionType, - fillColor: color, - child: child, - ); - }, + forwardBuilder: + (BuildContext context, Animation animation, Widget? child) { + return _EnterTransition( + animation: animation, + transitionType: transitionType, + reverse: true, + child: child, + ); + }, + reverseBuilder: + (BuildContext context, Animation animation, Widget? child) { + return _ExitTransition( + animation: animation, + transitionType: transitionType, + fillColor: color, + child: child, + ); + }, child: child, ), ); diff --git a/packages/animations/pubspec.yaml b/packages/animations/pubspec.yaml index 74fe71ac736..15be5e1714e 100644 --- a/packages/animations/pubspec.yaml +++ b/packages/animations/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.1.0 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/animations/test/dual_transition_builder_test.dart b/packages/animations/test/dual_transition_builder_test.dart index 93e7d8d4135..c8fd4cea946 100644 --- a/packages/animations/test/dual_transition_builder_test.dart +++ b/packages/animations/test/dual_transition_builder_test.dart @@ -16,23 +16,28 @@ void main() { Center( child: DualTransitionBuilder( animation: controller, - forwardBuilder: ( - BuildContext context, - Animation animation, - Widget? child, - ) { - return ScaleTransition(scale: animation, child: child); - }, - reverseBuilder: ( - BuildContext context, - Animation animation, - Widget? child, - ) { - return FadeTransition( - opacity: Tween(begin: 1.0, end: 0.0).animate(animation), - child: child, - ); - }, + forwardBuilder: + ( + BuildContext context, + Animation animation, + Widget? child, + ) { + return ScaleTransition(scale: animation, child: child); + }, + reverseBuilder: + ( + BuildContext context, + Animation animation, + Widget? child, + ) { + return FadeTransition( + opacity: Tween( + begin: 1.0, + end: 0.0, + ).animate(animation), + child: child, + ); + }, child: Container(color: Colors.green, height: 100, width: 100), ), ), @@ -81,23 +86,28 @@ void main() { child: Center( child: DualTransitionBuilder( animation: controller, - forwardBuilder: ( - BuildContext context, - Animation animation, - Widget? child, - ) { - return ScaleTransition(scale: animation, child: child); - }, - reverseBuilder: ( - BuildContext context, - Animation animation, - Widget? child, - ) { - return FadeTransition( - opacity: Tween(begin: 1.0, end: 0.0).animate(animation), - child: child, - ); - }, + forwardBuilder: + ( + BuildContext context, + Animation animation, + Widget? child, + ) { + return ScaleTransition(scale: animation, child: child); + }, + reverseBuilder: + ( + BuildContext context, + Animation animation, + Widget? child, + ) { + return FadeTransition( + opacity: Tween( + begin: 1.0, + end: 0.0, + ).animate(animation), + child: child, + ); + }, child: const _StatefulTestWidget(name: 'Foo'), ), ), @@ -144,23 +154,28 @@ void main() { Center( child: DualTransitionBuilder( animation: controller, - forwardBuilder: ( - BuildContext context, - Animation animation, - Widget? child, - ) { - return ScaleTransition(scale: animation, child: child); - }, - reverseBuilder: ( - BuildContext context, - Animation animation, - Widget? child, - ) { - return FadeTransition( - opacity: Tween(begin: 1.0, end: 0.0).animate(animation), - child: child, - ); - }, + forwardBuilder: + ( + BuildContext context, + Animation animation, + Widget? child, + ) { + return ScaleTransition(scale: animation, child: child); + }, + reverseBuilder: + ( + BuildContext context, + Animation animation, + Widget? child, + ) { + return FadeTransition( + opacity: Tween( + begin: 1.0, + end: 0.0, + ).animate(animation), + child: child, + ); + }, child: Container(color: Colors.green, height: 100, width: 100), ), ), @@ -206,23 +221,28 @@ void main() { Center( child: DualTransitionBuilder( animation: controller, - forwardBuilder: ( - BuildContext context, - Animation animation, - Widget? child, - ) { - return ScaleTransition(scale: animation, child: child); - }, - reverseBuilder: ( - BuildContext context, - Animation animation, - Widget? child, - ) { - return FadeTransition( - opacity: Tween(begin: 1.0, end: 0.0).animate(animation), - child: child, - ); - }, + forwardBuilder: + ( + BuildContext context, + Animation animation, + Widget? child, + ) { + return ScaleTransition(scale: animation, child: child); + }, + reverseBuilder: + ( + BuildContext context, + Animation animation, + Widget? child, + ) { + return FadeTransition( + opacity: Tween( + begin: 1.0, + end: 0.0, + ).animate(animation), + child: child, + ); + }, child: Container(color: Colors.green, height: 100, width: 100), ), ), diff --git a/packages/animations/test/fade_through_transition_test.dart b/packages/animations/test/fade_through_transition_test.dart index f84e5abb13f..82d26b6e552 100644 --- a/packages/animations/test/fade_through_transition_test.dart +++ b/packages/animations/test/fade_through_transition_test.dart @@ -472,9 +472,9 @@ class _TestWidget extends StatelessWidget { return contentBuilder != null ? contentBuilder!(settings) : Center( - key: ValueKey(settings.name), - child: Text(settings.name!), - ); + key: ValueKey(settings.name), + child: Text(settings.name!), + ); }, ); }, diff --git a/packages/animations/test/modal_test.dart b/packages/animations/test/modal_test.dart index e89b663fee1..2f3bbe90182 100644 --- a/packages/animations/test/modal_test.dart +++ b/packages/animations/test/modal_test.dart @@ -464,8 +464,9 @@ void main() { // Expect the last route pushed to the navigator to contain RouteSettings // equal to the RouteSettings passed to showModal - final ModalRoute modalRoute = - ModalRoute.of(tester.element(find.byType(_FlutterLogoModal)))!; + final ModalRoute modalRoute = ModalRoute.of( + tester.element(find.byType(_FlutterLogoModal)), + )!; expect(modalRoute.settings, routeSettings); }); diff --git a/packages/animations/test/open_container_test.dart b/packages/animations/test/open_container_test.dart index 1fe303b071c..916f5ed3f12 100644 --- a/packages/animations/test/open_container_test.dart +++ b/packages/animations/test/open_container_test.dart @@ -1538,15 +1538,13 @@ void main() { closedBuilder: (BuildContext context, VoidCallback action) { return GestureDetector(onTap: action, child: const Text('Closed')); }, - openBuilder: ( - BuildContext context, - CloseContainerActionCallback action, - ) { - return GestureDetector( - onTap: () => action(returnValue: true), - child: const Text('Open'), - ); - }, + openBuilder: + (BuildContext context, CloseContainerActionCallback action) { + return GestureDetector( + onTap: () => action(returnValue: true), + child: const Text('Open'), + ); + }, ); await tester.pumpWidget(_boilerplate(child: openContainer)); @@ -1578,23 +1576,20 @@ void main() { closedBuilder: (BuildContext context, VoidCallback action) { return Text('Close', key: closedBuilderKey); }, - openBuilder: ( - BuildContext context, - CloseContainerActionCallback action, - ) { - return const Text('Open'); - }, + openBuilder: + (BuildContext context, CloseContainerActionCallback action) { + return const Text('Open'); + }, ); await tester.pumpWidget(_boilerplate(child: openContainer)); - final Finder closedBuilderMaterial = - find - .ancestor( - of: find.byKey(closedBuilderKey), - matching: find.byType(Material), - ) - .first; + final Finder closedBuilderMaterial = find + .ancestor( + of: find.byKey(closedBuilderKey), + matching: find.byType(Material), + ) + .first; final Material material = tester.widget(closedBuilderMaterial); expect(material.clipBehavior, Clip.antiAlias); @@ -1606,24 +1601,21 @@ void main() { closedBuilder: (BuildContext context, VoidCallback action) { return Text('Close', key: closedBuilderKey); }, - openBuilder: ( - BuildContext context, - CloseContainerActionCallback action, - ) { - return const Text('Open'); - }, + openBuilder: + (BuildContext context, CloseContainerActionCallback action) { + return const Text('Open'); + }, clipBehavior: Clip.none, ); await tester.pumpWidget(_boilerplate(child: openContainer)); - final Finder closedBuilderMaterial = - find - .ancestor( - of: find.byKey(closedBuilderKey), - matching: find.byType(Material), - ) - .first; + final Finder closedBuilderMaterial = find + .ancestor( + of: find.byKey(closedBuilderKey), + matching: find.byType(Material), + ) + .first; final Material material = tester.widget(closedBuilderMaterial); expect(material.clipBehavior, Clip.none); @@ -1807,8 +1799,9 @@ void main() { // Expect the last route pushed to the navigator to contain RouteSettings // equal to the RouteSettings passed to the OpenContainer - final ModalRoute modalRoute = - ModalRoute.of(tester.element(find.text('Open')))!; + final ModalRoute modalRoute = ModalRoute.of( + tester.element(find.text('Open')), + )!; expect(modalRoute.settings, routeSettings); }); } @@ -1922,35 +1915,34 @@ class __RemoveOpenContainerExampleState return removeOpenContainerWidget ? const Text('Container has been removed') : OpenContainer( - closedBuilder: - (BuildContext context, VoidCallback action) => Column( - children: [ - const Text('Closed'), - ElevatedButton( - onPressed: action, - child: const Text('Open the container'), - ), - ], - ), - openBuilder: - (BuildContext context, VoidCallback action) => Column( - children: [ - const Text('Open'), - ElevatedButton( - onPressed: action, - child: const Text('Close the container'), - ), - ElevatedButton( - onPressed: () { - setState(() { - removeOpenContainerWidget = true; - }); - }, - child: const Text('Remove the container'), - ), - ], - ), - ); + closedBuilder: (BuildContext context, VoidCallback action) => + Column( + children: [ + const Text('Closed'), + ElevatedButton( + onPressed: action, + child: const Text('Open the container'), + ), + ], + ), + openBuilder: (BuildContext context, VoidCallback action) => Column( + children: [ + const Text('Open'), + ElevatedButton( + onPressed: action, + child: const Text('Close the container'), + ), + ElevatedButton( + onPressed: () { + setState(() { + removeOpenContainerWidget = true; + }); + }, + child: const Text('Remove the container'), + ), + ], + ), + ); } } diff --git a/packages/animations/test/shared_axis_transition_test.dart b/packages/animations/test/shared_axis_transition_test.dart index f251e21002a..db861390a6f 100644 --- a/packages/animations/test/shared_axis_transition_test.dart +++ b/packages/animations/test/shared_axis_transition_test.dart @@ -517,13 +517,12 @@ void main() { ); expect(find.text(bottomRoute), findsOneWidget); - Finder fillContainerFinder = - find - .ancestor( - matching: find.byType(ColoredBox), - of: find.byKey(const ValueKey('/')), - ) - .last; + Finder fillContainerFinder = find + .ancestor( + matching: find.byType(ColoredBox), + of: find.byKey(const ValueKey('/')), + ) + .last; expect(fillContainerFinder, findsOneWidget); expect( tester.widget(fillContainerFinder).color, @@ -534,13 +533,12 @@ void main() { await tester.pump(); await tester.pumpAndSettle(); - fillContainerFinder = - find - .ancestor( - matching: find.byType(ColoredBox), - of: find.byKey(const ValueKey('/a')), - ) - .last; + fillContainerFinder = find + .ancestor( + matching: find.byType(ColoredBox), + of: find.byKey(const ValueKey('/a')), + ) + .last; expect(fillContainerFinder, findsOneWidget); expect( tester.widget(fillContainerFinder).color, @@ -562,13 +560,12 @@ void main() { ); expect(find.text(bottomRoute), findsOneWidget); - Finder fillContainerFinder = - find - .ancestor( - matching: find.byType(ColoredBox), - of: find.byKey(const ValueKey('/')), - ) - .last; + Finder fillContainerFinder = find + .ancestor( + matching: find.byType(ColoredBox), + of: find.byKey(const ValueKey('/')), + ) + .last; expect(fillContainerFinder, findsOneWidget); expect( tester.widget(fillContainerFinder).color, @@ -579,13 +576,12 @@ void main() { await tester.pump(); await tester.pumpAndSettle(); - fillContainerFinder = - find - .ancestor( - matching: find.byType(ColoredBox), - of: find.byKey(const ValueKey('/a')), - ) - .last; + fillContainerFinder = find + .ancestor( + matching: find.byType(ColoredBox), + of: find.byKey(const ValueKey('/a')), + ) + .last; expect(fillContainerFinder, findsOneWidget); expect( tester.widget(fillContainerFinder).color, @@ -1171,13 +1167,12 @@ void main() { ); expect(find.text(bottomRoute), findsOneWidget); - Finder fillContainerFinder = - find - .ancestor( - matching: find.byType(ColoredBox), - of: find.byKey(const ValueKey('/')), - ) - .last; + Finder fillContainerFinder = find + .ancestor( + matching: find.byType(ColoredBox), + of: find.byKey(const ValueKey('/')), + ) + .last; expect(fillContainerFinder, findsOneWidget); expect( tester.widget(fillContainerFinder).color, @@ -1188,13 +1183,12 @@ void main() { await tester.pump(); await tester.pumpAndSettle(); - fillContainerFinder = - find - .ancestor( - matching: find.byType(ColoredBox), - of: find.byKey(const ValueKey('/a')), - ) - .last; + fillContainerFinder = find + .ancestor( + matching: find.byType(ColoredBox), + of: find.byKey(const ValueKey('/a')), + ) + .last; expect(fillContainerFinder, findsOneWidget); expect( tester.widget(fillContainerFinder).color, @@ -1216,13 +1210,12 @@ void main() { ); expect(find.text(bottomRoute), findsOneWidget); - Finder fillContainerFinder = - find - .ancestor( - matching: find.byType(ColoredBox), - of: find.byKey(const ValueKey('/')), - ) - .last; + Finder fillContainerFinder = find + .ancestor( + matching: find.byType(ColoredBox), + of: find.byKey(const ValueKey('/')), + ) + .last; expect(fillContainerFinder, findsOneWidget); expect( tester.widget(fillContainerFinder).color, @@ -1233,13 +1226,12 @@ void main() { await tester.pump(); await tester.pumpAndSettle(); - fillContainerFinder = - find - .ancestor( - matching: find.byType(ColoredBox), - of: find.byKey(const ValueKey('/a')), - ) - .last; + fillContainerFinder = find + .ancestor( + matching: find.byType(ColoredBox), + of: find.byKey(const ValueKey('/a')), + ) + .last; expect(fillContainerFinder, findsOneWidget); expect( tester.widget(fillContainerFinder).color, @@ -1715,13 +1707,12 @@ void main() { ); expect(find.text(bottomRoute), findsOneWidget); - Finder fillContainerFinder = - find - .ancestor( - matching: find.byType(ColoredBox), - of: find.byKey(const ValueKey('/')), - ) - .last; + Finder fillContainerFinder = find + .ancestor( + matching: find.byType(ColoredBox), + of: find.byKey(const ValueKey('/')), + ) + .last; expect(fillContainerFinder, findsOneWidget); expect( tester.widget(fillContainerFinder).color, @@ -1732,13 +1723,12 @@ void main() { await tester.pump(); await tester.pumpAndSettle(); - fillContainerFinder = - find - .ancestor( - matching: find.byType(ColoredBox), - of: find.byKey(const ValueKey('/a')), - ) - .last; + fillContainerFinder = find + .ancestor( + matching: find.byType(ColoredBox), + of: find.byKey(const ValueKey('/a')), + ) + .last; expect(fillContainerFinder, findsOneWidget); expect( tester.widget(fillContainerFinder).color, @@ -1760,13 +1750,12 @@ void main() { ); expect(find.text(bottomRoute), findsOneWidget); - Finder fillContainerFinder = - find - .ancestor( - matching: find.byType(ColoredBox), - of: find.byKey(const ValueKey('/')), - ) - .last; + Finder fillContainerFinder = find + .ancestor( + matching: find.byType(ColoredBox), + of: find.byKey(const ValueKey('/')), + ) + .last; expect(fillContainerFinder, findsOneWidget); expect( tester.widget(fillContainerFinder).color, @@ -1777,13 +1766,12 @@ void main() { await tester.pump(); await tester.pumpAndSettle(); - fillContainerFinder = - find - .ancestor( - matching: find.byType(ColoredBox), - of: find.byKey(const ValueKey('/a')), - ) - .last; + fillContainerFinder = find + .ancestor( + matching: find.byType(ColoredBox), + of: find.byKey(const ValueKey('/a')), + ) + .last; expect(fillContainerFinder, findsOneWidget); expect( tester.widget(fillContainerFinder).color, @@ -1956,9 +1944,9 @@ class _TestWidget extends StatelessWidget { return contentBuilder != null ? contentBuilder!(settings) : Center( - key: ValueKey(settings.name), - child: Text(settings.name!), - ); + key: ValueKey(settings.name), + child: Text(settings.name!), + ); }, ); }, diff --git a/packages/camera/camera/CHANGELOG.md b/packages/camera/camera/CHANGELOG.md index a04de5b7c64..cbb5031f6da 100644 --- a/packages/camera/camera/CHANGELOG.md +++ b/packages/camera/camera/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. + ## 0.11.3 * Adds support to configure persistent recording on Android. See `CameraController.startVideoRecording(enablePersistentRecording)`. diff --git a/packages/camera/camera/example/integration_test/camera_test.dart b/packages/camera/camera/example/integration_test/camera_test.dart index 19909e55a89..c12e5880bd5 100644 --- a/packages/camera/camera/example/integration_test/camera_test.dart +++ b/packages/camera/camera/example/integration_test/camera_test.dart @@ -33,10 +33,12 @@ void main() { final Map presetExpectedSizes = { - ResolutionPreset.low: - Platform.isAndroid ? const Size(240, 320) : const Size(288, 352), - ResolutionPreset.medium: - Platform.isAndroid ? const Size(480, 720) : const Size(480, 640), + ResolutionPreset.low: Platform.isAndroid + ? const Size(240, 320) + : const Size(288, 352), + ResolutionPreset.medium: Platform.isAndroid + ? const Size(480, 720) + : const Size(480, 640), ResolutionPreset.high: const Size(720, 1280), ResolutionPreset.veryHigh: const Size(1080, 1920), ResolutionPreset.ultraHigh: const Size(2160, 3840), diff --git a/packages/camera/camera/example/lib/main.dart b/packages/camera/camera/example/lib/main.dart index ddd533c20de..f8d4c8c44dc 100644 --- a/packages/camera/camera/example/lib/main.dart +++ b/packages/camera/camera/example/lib/main.dart @@ -142,8 +142,8 @@ class _CameraExampleHomeState extends State border: Border.all( color: controller != null && controller!.value.isRecordingVideo - ? Colors.redAccent - : Colors.grey, + ? Colors.redAccent + : Colors.grey, width: 3.0, ), ), @@ -191,9 +191,8 @@ class _CameraExampleHomeState extends State behavior: HitTestBehavior.opaque, onScaleStart: _handleScaleStart, onScaleUpdate: _handleScaleUpdate, - onTapDown: - (TapDownDetails details) => - onViewFinderTap(details, constraints), + onTapDown: (TapDownDetails details) => + onViewFinderTap(details, constraints), ); }, ), @@ -267,19 +266,21 @@ class _CameraExampleHomeState extends State // The exposure and focus mode are currently not supported on the web. ...!kIsWeb ? [ - IconButton( - icon: const Icon(Icons.exposure), - color: Colors.blue, - onPressed: - controller != null ? onExposureModeButtonPressed : null, - ), - IconButton( - icon: const Icon(Icons.filter_center_focus), - color: Colors.blue, - onPressed: - controller != null ? onFocusModeButtonPressed : null, - ), - ] + IconButton( + icon: const Icon(Icons.exposure), + color: Colors.blue, + onPressed: controller != null + ? onExposureModeButtonPressed + : null, + ), + IconButton( + icon: const Icon(Icons.filter_center_focus), + color: Colors.blue, + onPressed: controller != null + ? onFocusModeButtonPressed + : null, + ), + ] : [], IconButton( icon: Icon(enableAudio ? Icons.volume_up : Icons.volume_mute), @@ -293,10 +294,9 @@ class _CameraExampleHomeState extends State : Icons.screen_rotation, ), color: Colors.blue, - onPressed: - controller != null - ? onCaptureOrientationLockButtonPressed - : null, + onPressed: controller != null + ? onCaptureOrientationLockButtonPressed + : null, ), ], ), @@ -316,47 +316,39 @@ class _CameraExampleHomeState extends State children: [ IconButton( icon: const Icon(Icons.flash_off), - color: - controller?.value.flashMode == FlashMode.off - ? Colors.orange - : Colors.blue, - onPressed: - controller != null - ? () => onSetFlashModeButtonPressed(FlashMode.off) - : null, + color: controller?.value.flashMode == FlashMode.off + ? Colors.orange + : Colors.blue, + onPressed: controller != null + ? () => onSetFlashModeButtonPressed(FlashMode.off) + : null, ), IconButton( icon: const Icon(Icons.flash_auto), - color: - controller?.value.flashMode == FlashMode.auto - ? Colors.orange - : Colors.blue, - onPressed: - controller != null - ? () => onSetFlashModeButtonPressed(FlashMode.auto) - : null, + color: controller?.value.flashMode == FlashMode.auto + ? Colors.orange + : Colors.blue, + onPressed: controller != null + ? () => onSetFlashModeButtonPressed(FlashMode.auto) + : null, ), IconButton( icon: const Icon(Icons.flash_on), - color: - controller?.value.flashMode == FlashMode.always - ? Colors.orange - : Colors.blue, - onPressed: - controller != null - ? () => onSetFlashModeButtonPressed(FlashMode.always) - : null, + color: controller?.value.flashMode == FlashMode.always + ? Colors.orange + : Colors.blue, + onPressed: controller != null + ? () => onSetFlashModeButtonPressed(FlashMode.always) + : null, ), IconButton( icon: const Icon(Icons.highlight), - color: - controller?.value.flashMode == FlashMode.torch - ? Colors.orange - : Colors.blue, - onPressed: - controller != null - ? () => onSetFlashModeButtonPressed(FlashMode.torch) - : null, + color: controller?.value.flashMode == FlashMode.torch + ? Colors.orange + : Colors.blue, + onPressed: controller != null + ? () => onSetFlashModeButtonPressed(FlashMode.torch) + : null, ), ], ), @@ -366,16 +358,14 @@ class _CameraExampleHomeState extends State Widget _exposureModeControlRowWidget() { final ButtonStyle styleAuto = TextButton.styleFrom( - foregroundColor: - controller?.value.exposureMode == ExposureMode.auto - ? Colors.orange - : Colors.blue, + foregroundColor: controller?.value.exposureMode == ExposureMode.auto + ? Colors.orange + : Colors.blue, ); final ButtonStyle styleLocked = TextButton.styleFrom( - foregroundColor: - controller?.value.exposureMode == ExposureMode.locked - ? Colors.orange - : Colors.blue, + foregroundColor: controller?.value.exposureMode == ExposureMode.locked + ? Colors.orange + : Colors.blue, ); return SizeTransition( @@ -391,12 +381,10 @@ class _CameraExampleHomeState extends State children: [ TextButton( style: styleAuto, - onPressed: - controller != null - ? () => onSetExposureModeButtonPressed( - ExposureMode.auto, - ) - : null, + onPressed: controller != null + ? () => + onSetExposureModeButtonPressed(ExposureMode.auto) + : null, onLongPress: () { if (controller != null) { controller!.setExposurePoint(null); @@ -407,20 +395,18 @@ class _CameraExampleHomeState extends State ), TextButton( style: styleLocked, - onPressed: - controller != null - ? () => onSetExposureModeButtonPressed( - ExposureMode.locked, - ) - : null, + onPressed: controller != null + ? () => onSetExposureModeButtonPressed( + ExposureMode.locked, + ) + : null, child: const Text('LOCKED'), ), TextButton( style: styleLocked, - onPressed: - controller != null - ? () => controller!.setExposureOffset(0.0) - : null, + onPressed: controller != null + ? () => controller!.setExposureOffset(0.0) + : null, child: const Text('RESET OFFSET'), ), ], @@ -437,9 +423,9 @@ class _CameraExampleHomeState extends State label: _currentExposureOffset.toString(), onChanged: _minAvailableExposureOffset == - _maxAvailableExposureOffset - ? null - : setExposureOffset, + _maxAvailableExposureOffset + ? null + : setExposureOffset, ), Text(_maxAvailableExposureOffset.toString()), ], @@ -453,16 +439,14 @@ class _CameraExampleHomeState extends State Widget _focusModeControlRowWidget() { final ButtonStyle styleAuto = TextButton.styleFrom( - foregroundColor: - controller?.value.focusMode == FocusMode.auto - ? Colors.orange - : Colors.blue, + foregroundColor: controller?.value.focusMode == FocusMode.auto + ? Colors.orange + : Colors.blue, ); final ButtonStyle styleLocked = TextButton.styleFrom( - foregroundColor: - controller?.value.focusMode == FocusMode.locked - ? Colors.orange - : Colors.blue, + foregroundColor: controller?.value.focusMode == FocusMode.locked + ? Colors.orange + : Colors.blue, ); return SizeTransition( @@ -478,10 +462,9 @@ class _CameraExampleHomeState extends State children: [ TextButton( style: styleAuto, - onPressed: - controller != null - ? () => onSetFocusModeButtonPressed(FocusMode.auto) - : null, + onPressed: controller != null + ? () => onSetFocusModeButtonPressed(FocusMode.auto) + : null, onLongPress: () { if (controller != null) { controller!.setFocusPoint(null); @@ -492,11 +475,9 @@ class _CameraExampleHomeState extends State ), TextButton( style: styleLocked, - onPressed: - controller != null - ? () => - onSetFocusModeButtonPressed(FocusMode.locked) - : null, + onPressed: controller != null + ? () => onSetFocusModeButtonPressed(FocusMode.locked) + : null, child: const Text('LOCKED'), ), ], @@ -520,55 +501,56 @@ class _CameraExampleHomeState extends State color: Colors.blue, onPressed: cameraController != null && - cameraController.value.isInitialized && - !cameraController.value.isRecordingVideo - ? onTakePictureButtonPressed - : null, + cameraController.value.isInitialized && + !cameraController.value.isRecordingVideo + ? onTakePictureButtonPressed + : null, ), IconButton( icon: const Icon(Icons.videocam), color: Colors.blue, onPressed: cameraController != null && - cameraController.value.isInitialized && - !cameraController.value.isRecordingVideo - ? onVideoRecordButtonPressed - : null, + cameraController.value.isInitialized && + !cameraController.value.isRecordingVideo + ? onVideoRecordButtonPressed + : null, ), IconButton( icon: cameraController != null && - cameraController.value.isRecordingPaused - ? const Icon(Icons.play_arrow) - : const Icon(Icons.pause), + cameraController.value.isRecordingPaused + ? const Icon(Icons.play_arrow) + : const Icon(Icons.pause), color: Colors.blue, onPressed: cameraController != null && - cameraController.value.isInitialized && - cameraController.value.isRecordingVideo - ? cameraController.value.isRecordingPaused - ? onResumeButtonPressed - : onPauseButtonPressed - : null, + cameraController.value.isInitialized && + cameraController.value.isRecordingVideo + ? cameraController.value.isRecordingPaused + ? onResumeButtonPressed + : onPauseButtonPressed + : null, ), IconButton( icon: const Icon(Icons.stop), color: Colors.red, onPressed: cameraController != null && - cameraController.value.isInitialized && - cameraController.value.isRecordingVideo - ? onStopButtonPressed - : null, + cameraController.value.isInitialized && + cameraController.value.isRecordingVideo + ? onStopButtonPressed + : null, ), IconButton( icon: const Icon(Icons.pause_presentation), color: cameraController != null && cameraController.value.isPreviewPaused - ? Colors.red - : Colors.blue, - onPressed: - cameraController == null ? null : onPausePreviewButtonPressed, + ? Colors.red + : Colors.blue, + onPressed: cameraController == null + ? null + : onPausePreviewButtonPressed, ), ], ); @@ -678,13 +660,13 @@ class _CameraExampleHomeState extends State // The exposure mode is currently not supported on the web. ...!kIsWeb ? >[ - cameraController.getMinExposureOffset().then( - (double value) => _minAvailableExposureOffset = value, - ), - cameraController.getMaxExposureOffset().then( - (double value) => _maxAvailableExposureOffset = value, - ), - ] + cameraController.getMinExposureOffset().then( + (double value) => _minAvailableExposureOffset = value, + ), + cameraController.getMaxExposureOffset().then( + (double value) => _maxAvailableExposureOffset = value, + ), + ] : >[], cameraController.getMaxZoomLevel().then( (double value) => _maxAvailableZoom = value, @@ -1003,10 +985,9 @@ class _CameraExampleHomeState extends State return; } - final VideoPlayerController vController = - kIsWeb - ? VideoPlayerController.networkUrl(Uri.parse(videoFile!.path)) - : VideoPlayerController.file(File(videoFile!.path)); + final VideoPlayerController vController = kIsWeb + ? VideoPlayerController.networkUrl(Uri.parse(videoFile!.path)) + : VideoPlayerController.file(File(videoFile!.path)); videoPlayerListener = () { if (videoController != null) { diff --git a/packages/camera/camera/example/pubspec.yaml b/packages/camera/camera/example/pubspec.yaml index e268268e320..34003f4bea6 100644 --- a/packages/camera/camera/example/pubspec.yaml +++ b/packages/camera/camera/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the camera plugin. publish_to: none environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: camera: diff --git a/packages/camera/camera_platform_interface/CHANGELOG.md b/packages/camera/camera_platform_interface/CHANGELOG.md index 7c011acbcbe..4293013ddeb 100644 --- a/packages/camera/camera_platform_interface/CHANGELOG.md +++ b/packages/camera/camera_platform_interface/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. + ## 2.12.0 * Adds support for video stabilization. diff --git a/packages/camera/camera_platform_interface/lib/src/events/camera_event.dart b/packages/camera/camera_platform_interface/lib/src/events/camera_event.dart index 397a901dcb2..78cd0ac4fd4 100644 --- a/packages/camera/camera_platform_interface/lib/src/events/camera_event.dart +++ b/packages/camera/camera_platform_interface/lib/src/events/camera_event.dart @@ -252,10 +252,9 @@ class VideoRecordedEvent extends CameraEvent { /// class. VideoRecordedEvent.fromJson(Map json) : file = XFile(json['path']! as String), - maxVideoDuration = - json['maxVideoDuration'] != null - ? Duration(milliseconds: json['maxVideoDuration'] as int) - : null, + maxVideoDuration = json['maxVideoDuration'] != null + ? Duration(milliseconds: json['maxVideoDuration'] as int) + : null, super(json['cameraId']! as int); /// XFile of the recorded video. diff --git a/packages/camera/camera_platform_interface/lib/src/method_channel/method_channel_camera.dart b/packages/camera/camera_platform_interface/lib/src/method_channel/method_channel_camera.dart index 8cc6ec4f981..d48b06023f1 100644 --- a/packages/camera/camera_platform_interface/lib/src/method_channel/method_channel_camera.dart +++ b/packages/camera/camera_platform_interface/lib/src/method_channel/method_channel_camera.dart @@ -106,12 +106,9 @@ class MethodChannelCamera extends CameraPlatform { final Map? reply = await _channel .invokeMapMethod('create', { 'cameraName': cameraDescription.name, - 'resolutionPreset': - resolutionPreset != null - ? _serializeResolutionPreset( - mediaSettings.resolutionPreset!, - ) - : null, + 'resolutionPreset': resolutionPreset != null + ? _serializeResolutionPreset(mediaSettings.resolutionPreset!) + : null, 'fps': mediaSettings.fps, 'videoBitrate': mediaSettings.videoBitrate, 'audioBitrate': mediaSettings.audioBitrate, diff --git a/packages/camera/camera_platform_interface/pubspec.yaml b/packages/camera/camera_platform_interface/pubspec.yaml index f3e45edb835..9d8e8c97665 100644 --- a/packages/camera/camera_platform_interface/pubspec.yaml +++ b/packages/camera/camera_platform_interface/pubspec.yaml @@ -7,8 +7,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.12.0 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: cross_file: ^0.3.1 diff --git a/packages/camera/camera_platform_interface/test/method_channel/method_channel_camera_test.dart b/packages/camera/camera_platform_interface/test/method_channel/method_channel_camera_test.dart index c60e3e6cb4c..78cf02f8069 100644 --- a/packages/camera/camera_platform_interface/test/method_channel/method_channel_camera_test.dart +++ b/packages/camera/camera_platform_interface/test/method_channel/method_channel_camera_test.dart @@ -484,8 +484,8 @@ void main() { test('Should receive device orientation change events', () async { // Act - final Stream eventStream = - camera.onDeviceOrientationChanged(); + final Stream eventStream = camera + .onDeviceOrientationChanged(); final StreamQueue streamQueue = StreamQueue(eventStream); @@ -576,8 +576,8 @@ void main() { ); // Act - final List cameras = - await camera.availableCameras(); + final List cameras = await camera + .availableCameras(); // Assert expect(channel.log, [ diff --git a/packages/camera/camera_web/CHANGELOG.md b/packages/camera/camera_web/CHANGELOG.md index 0bfdbd06124..47a3f6ee516 100644 --- a/packages/camera/camera_web/CHANGELOG.md +++ b/packages/camera/camera_web/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 0.3.5 diff --git a/packages/camera/camera_web/example/integration_test/camera_bitrate_test.dart b/packages/camera/camera_web/example/integration_test/camera_bitrate_test.dart index 9d240bba078..c6547ca28bf 100644 --- a/packages/camera/camera_web/example/integration_test/camera_bitrate_test.dart +++ b/packages/camera/camera_web/example/integration_test/camera_bitrate_test.dart @@ -66,11 +66,10 @@ void main() { mockWindow.navigator = navigator; mockNavigator.mediaDevices = mediaDevices; - final HTMLCanvasElement canvasElement = - HTMLCanvasElement() - ..width = videoSize.width.toInt() - ..height = videoSize.height.toInt() - ..context2D.clearRect(0, 0, videoSize.width, videoSize.height); + final HTMLCanvasElement canvasElement = HTMLCanvasElement() + ..width = videoSize.width.toInt() + ..height = videoSize.height.toInt() + ..context2D.clearRect(0, 0, videoSize.width, videoSize.height); final HTMLVideoElement videoElement = HTMLVideoElement(); diff --git a/packages/camera/camera_web/example/integration_test/camera_service_test.dart b/packages/camera/camera_web/example/integration_test/camera_service_test.dart index 0be8bf3a12a..485fcac5508 100644 --- a/packages/camera/camera_web/example/integration_test/camera_service_test.dart +++ b/packages/camera/camera_web/example/integration_test/camera_service_test.dart @@ -67,16 +67,14 @@ void main() { testWidgets('calls MediaDevices.getUserMedia ' 'with provided options', (WidgetTester tester) async { late final web.MediaStreamConstraints? capturedConstraints; - mockMediaDevices.getUserMedia = - ([web.MediaStreamConstraints? constraints]) { - capturedConstraints = constraints; - final web.MediaStream stream = - createJSInteropWrapper( - FakeMediaStream([]), - ) - as web.MediaStream; - return Future.value(stream).toJS; - }.toJS; + mockMediaDevices + .getUserMedia = ([web.MediaStreamConstraints? constraints]) { + capturedConstraints = constraints; + final web.MediaStream stream = + createJSInteropWrapper(FakeMediaStream([])) + as web.MediaStream; + return Future.value(stream).toJS; + }.toJS; final CameraOptions options = CameraOptions( video: VideoConstraints( @@ -101,12 +99,11 @@ void main() { testWidgets('with notFound error ' 'when MediaDevices.getUserMedia throws DomException ' 'with NotFoundError', (WidgetTester tester) async { - mockMediaDevices.getUserMedia = - ([web.MediaStreamConstraints? _]) { - throw web.DOMException('', 'NotFoundError'); - // ignore: dead_code - return Future.value(web.MediaStream()).toJS; - }.toJS; + mockMediaDevices.getUserMedia = ([web.MediaStreamConstraints? _]) { + throw web.DOMException('', 'NotFoundError'); + // ignore: dead_code + return Future.value(web.MediaStream()).toJS; + }.toJS; expect( () => cameraService.getMediaStreamForOptions( @@ -132,12 +129,11 @@ void main() { testWidgets('with notFound error ' 'when MediaDevices.getUserMedia throws DomException ' 'with DevicesNotFoundError', (WidgetTester tester) async { - mockMediaDevices.getUserMedia = - ([web.MediaStreamConstraints? _]) { - throw web.DOMException('', 'DevicesNotFoundError'); - // ignore: dead_code - return Future.value(web.MediaStream()).toJS; - }.toJS; + mockMediaDevices.getUserMedia = ([web.MediaStreamConstraints? _]) { + throw web.DOMException('', 'DevicesNotFoundError'); + // ignore: dead_code + return Future.value(web.MediaStream()).toJS; + }.toJS; expect( () => cameraService.getMediaStreamForOptions( @@ -163,12 +159,11 @@ void main() { testWidgets('with notReadable error ' 'when MediaDevices.getUserMedia throws DomException ' 'with NotReadableError', (WidgetTester tester) async { - mockMediaDevices.getUserMedia = - ([web.MediaStreamConstraints? _]) { - throw web.DOMException('', 'NotReadableError'); - // ignore: dead_code - return Future.value(web.MediaStream()).toJS; - }.toJS; + mockMediaDevices.getUserMedia = ([web.MediaStreamConstraints? _]) { + throw web.DOMException('', 'NotReadableError'); + // ignore: dead_code + return Future.value(web.MediaStream()).toJS; + }.toJS; expect( () => cameraService.getMediaStreamForOptions( const CameraOptions(), @@ -193,12 +188,11 @@ void main() { testWidgets('with notReadable error ' 'when MediaDevices.getUserMedia throws DomException ' 'with TrackStartError', (WidgetTester tester) async { - mockMediaDevices.getUserMedia = - ([web.MediaStreamConstraints? _]) { - throw web.DOMException('', 'TrackStartError'); - // ignore: dead_code - return Future.value(web.MediaStream()).toJS; - }.toJS; + mockMediaDevices.getUserMedia = ([web.MediaStreamConstraints? _]) { + throw web.DOMException('', 'TrackStartError'); + // ignore: dead_code + return Future.value(web.MediaStream()).toJS; + }.toJS; expect( () => cameraService.getMediaStreamForOptions( @@ -224,12 +218,11 @@ void main() { testWidgets('with overconstrained error ' 'when MediaDevices.getUserMedia throws DomException ' 'with OverconstrainedError', (WidgetTester tester) async { - mockMediaDevices.getUserMedia = - ([web.MediaStreamConstraints? _]) { - throw web.DOMException('', 'OverconstrainedError'); - // ignore: dead_code - return Future.value(web.MediaStream()).toJS; - }.toJS; + mockMediaDevices.getUserMedia = ([web.MediaStreamConstraints? _]) { + throw web.DOMException('', 'OverconstrainedError'); + // ignore: dead_code + return Future.value(web.MediaStream()).toJS; + }.toJS; expect( () => cameraService.getMediaStreamForOptions( @@ -255,12 +248,11 @@ void main() { testWidgets('with overconstrained error ' 'when MediaDevices.getUserMedia throws DomException ' 'with ConstraintNotSatisfiedError', (WidgetTester tester) async { - mockMediaDevices.getUserMedia = - ([web.MediaStreamConstraints? _]) { - throw web.DOMException('', 'ConstraintNotSatisfiedError'); - // ignore: dead_code - return Future.value(web.MediaStream()).toJS; - }.toJS; + mockMediaDevices.getUserMedia = ([web.MediaStreamConstraints? _]) { + throw web.DOMException('', 'ConstraintNotSatisfiedError'); + // ignore: dead_code + return Future.value(web.MediaStream()).toJS; + }.toJS; expect( () => cameraService.getMediaStreamForOptions( @@ -286,12 +278,11 @@ void main() { testWidgets('with permissionDenied error ' 'when MediaDevices.getUserMedia throws DomException ' 'with NotAllowedError', (WidgetTester tester) async { - mockMediaDevices.getUserMedia = - ([web.MediaStreamConstraints? _]) { - throw web.DOMException('', 'NotAllowedError'); - // ignore: dead_code - return Future.value(web.MediaStream()).toJS; - }.toJS; + mockMediaDevices.getUserMedia = ([web.MediaStreamConstraints? _]) { + throw web.DOMException('', 'NotAllowedError'); + // ignore: dead_code + return Future.value(web.MediaStream()).toJS; + }.toJS; expect( () => cameraService.getMediaStreamForOptions( @@ -317,12 +308,11 @@ void main() { testWidgets('with permissionDenied error ' 'when MediaDevices.getUserMedia throws DomException ' 'with PermissionDeniedError', (WidgetTester tester) async { - mockMediaDevices.getUserMedia = - ([web.MediaStreamConstraints? _]) { - throw web.DOMException('', 'PermissionDeniedError'); - // ignore: dead_code - return Future.value(web.MediaStream()).toJS; - }.toJS; + mockMediaDevices.getUserMedia = ([web.MediaStreamConstraints? _]) { + throw web.DOMException('', 'PermissionDeniedError'); + // ignore: dead_code + return Future.value(web.MediaStream()).toJS; + }.toJS; expect( () => cameraService.getMediaStreamForOptions( @@ -348,12 +338,11 @@ void main() { testWidgets('with type error ' 'when MediaDevices.getUserMedia throws DomException ' 'with TypeError', (WidgetTester tester) async { - mockMediaDevices.getUserMedia = - ([web.MediaStreamConstraints? _]) { - throw web.DOMException('', 'TypeError'); - // ignore: dead_code - return Future.value(web.MediaStream()).toJS; - }.toJS; + mockMediaDevices.getUserMedia = ([web.MediaStreamConstraints? _]) { + throw web.DOMException('', 'TypeError'); + // ignore: dead_code + return Future.value(web.MediaStream()).toJS; + }.toJS; expect( () => cameraService.getMediaStreamForOptions( @@ -379,12 +368,11 @@ void main() { testWidgets('with abort error ' 'when MediaDevices.getUserMedia throws DomException ' 'with AbortError', (WidgetTester tester) async { - mockMediaDevices.getUserMedia = - ([web.MediaStreamConstraints? _]) { - throw web.DOMException('', 'AbortError'); - // ignore: dead_code - return Future.value(web.MediaStream()).toJS; - }.toJS; + mockMediaDevices.getUserMedia = ([web.MediaStreamConstraints? _]) { + throw web.DOMException('', 'AbortError'); + // ignore: dead_code + return Future.value(web.MediaStream()).toJS; + }.toJS; expect( () => cameraService.getMediaStreamForOptions( @@ -410,12 +398,11 @@ void main() { testWidgets('with security error ' 'when MediaDevices.getUserMedia throws DomException ' 'with SecurityError', (WidgetTester tester) async { - mockMediaDevices.getUserMedia = - ([web.MediaStreamConstraints? _]) { - throw web.DOMException('', 'SecurityError'); - // ignore: dead_code - return Future.value(web.MediaStream()).toJS; - }.toJS; + mockMediaDevices.getUserMedia = ([web.MediaStreamConstraints? _]) { + throw web.DOMException('', 'SecurityError'); + // ignore: dead_code + return Future.value(web.MediaStream()).toJS; + }.toJS; expect( () => cameraService.getMediaStreamForOptions( @@ -441,12 +428,11 @@ void main() { testWidgets('with unknown error ' 'when MediaDevices.getUserMedia throws DomException ' 'with an unknown error', (WidgetTester tester) async { - mockMediaDevices.getUserMedia = - ([web.MediaStreamConstraints? _]) { - throw web.DOMException('', 'Unknown'); - // ignore: dead_code - return Future.value(web.MediaStream()).toJS; - }.toJS; + mockMediaDevices.getUserMedia = ([web.MediaStreamConstraints? _]) { + throw web.DOMException('', 'Unknown'); + // ignore: dead_code + return Future.value(web.MediaStream()).toJS; + }.toJS; expect( () => cameraService.getMediaStreamForOptions( @@ -473,12 +459,11 @@ void main() { 'when MediaDevices.getUserMedia throws an unknown exception', ( WidgetTester tester, ) async { - mockMediaDevices.getUserMedia = - ([web.MediaStreamConstraints? _]) { - throw Exception(); - // ignore: dead_code - return Future.value(web.MediaStream()).toJS; - }.toJS; + mockMediaDevices.getUserMedia = ([web.MediaStreamConstraints? _]) { + throw Exception(); + // ignore: dead_code + return Future.value(web.MediaStream()).toJS; + }.toJS; expect( () => cameraService.getMediaStreamForOptions( @@ -528,17 +513,15 @@ void main() { testWidgets('returns the zoom level capability ' 'based on the first video track', (WidgetTester tester) async { - mockMediaDevices.getSupportedConstraints = - () { - return web.MediaTrackSupportedConstraints(zoom: true); - }.toJS; - - mockVideoTrack.getCapabilities = - () { - return web.MediaTrackCapabilities( - zoom: web.MediaSettingsRange(min: 100, max: 400, step: 2), - ); - }.toJS; + mockMediaDevices.getSupportedConstraints = () { + return web.MediaTrackSupportedConstraints(zoom: true); + }.toJS; + + mockVideoTrack.getCapabilities = () { + return web.MediaTrackCapabilities( + zoom: web.MediaSettingsRange(min: 100, max: 400, step: 2), + ); + }.toJS; final ZoomLevelCapability zoomLevelCapability = cameraService .getZoomLevelCapabilityForCamera(camera); @@ -552,17 +535,15 @@ void main() { testWidgets('with zoomLevelNotSupported error ' 'when the zoom level is not supported ' 'in the browser', (WidgetTester tester) async { - mockMediaDevices.getSupportedConstraints = - () { - return web.MediaTrackSupportedConstraints(zoom: false); - }.toJS; - - mockVideoTrack.getCapabilities = - () { - return web.MediaTrackCapabilities( - zoom: web.MediaSettingsRange(min: 100, max: 400, step: 2), - ); - }.toJS; + mockMediaDevices.getSupportedConstraints = () { + return web.MediaTrackSupportedConstraints(zoom: false); + }.toJS; + + mockVideoTrack.getCapabilities = () { + return web.MediaTrackCapabilities( + zoom: web.MediaSettingsRange(min: 100, max: 400, step: 2), + ); + }.toJS; expect( () => cameraService.getZoomLevelCapabilityForCamera(camera), @@ -586,10 +567,9 @@ void main() { 'when the camera stream has not been initialized', ( WidgetTester tester, ) async { - mockMediaDevices.getSupportedConstraints = - () { - return web.MediaTrackSupportedConstraints(zoom: true); - }.toJS; + mockMediaDevices.getSupportedConstraints = () { + return web.MediaTrackSupportedConstraints(zoom: true); + }.toJS; // Create a camera stream with no video tracks. when(camera.stream).thenReturn( @@ -624,10 +604,9 @@ void main() { testWidgets('returns null ' 'when the facing mode is not supported', (WidgetTester tester) async { - mockMediaDevices.getSupportedConstraints = - () { - return web.MediaTrackSupportedConstraints(facingMode: false); - }.toJS; + mockMediaDevices.getSupportedConstraints = () { + return web.MediaTrackSupportedConstraints(facingMode: false); + }.toJS; final String? facingMode = cameraService.getFacingModeForVideoTrack( createJSInteropWrapper(MockMediaStreamTrack()) @@ -650,18 +629,16 @@ void main() { jsUtil.hasProperty(videoTrack, 'getCapabilities'.toJS), ).thenReturn(true); - mockMediaDevices.getSupportedConstraints = - () { - return web.MediaTrackSupportedConstraints(facingMode: true); - }.toJS; + mockMediaDevices.getSupportedConstraints = () { + return web.MediaTrackSupportedConstraints(facingMode: true); + }.toJS; }); testWidgets('returns an appropriate facing mode ' 'based on the video track settings', (WidgetTester tester) async { - mockVideoTrack.getSettings = - () { - return web.MediaTrackSettings(facingMode: 'user'); - }.toJS; + mockVideoTrack.getSettings = () { + return web.MediaTrackSettings(facingMode: 'user'); + }.toJS; final String? facingMode = cameraService.getFacingModeForVideoTrack( videoTrack, @@ -675,16 +652,14 @@ void main() { 'when the facing mode setting is empty', ( WidgetTester tester, ) async { - mockVideoTrack.getSettings = - () { - return web.MediaTrackSettings(facingMode: ''); - }.toJS; - mockVideoTrack.getCapabilities = - () { - return web.MediaTrackCapabilities( - facingMode: ['environment'.toJS, 'left'.toJS].toJS, - ); - }.toJS; + mockVideoTrack.getSettings = () { + return web.MediaTrackSettings(facingMode: ''); + }.toJS; + mockVideoTrack.getCapabilities = () { + return web.MediaTrackCapabilities( + facingMode: ['environment'.toJS, 'left'.toJS].toJS, + ); + }.toJS; when( jsUtil.hasProperty(videoTrack, 'getCapabilities'.toJS), @@ -700,16 +675,12 @@ void main() { testWidgets('returns null ' 'when the facing mode setting ' 'and capabilities are empty', (WidgetTester tester) async { - mockVideoTrack.getSettings = - () { - return web.MediaTrackSettings(facingMode: ''); - }.toJS; - mockVideoTrack.getCapabilities = - () { - return web.MediaTrackCapabilities( - facingMode: [].toJS, - ); - }.toJS; + mockVideoTrack.getSettings = () { + return web.MediaTrackSettings(facingMode: ''); + }.toJS; + mockVideoTrack.getCapabilities = () { + return web.MediaTrackCapabilities(facingMode: [].toJS); + }.toJS; final String? facingMode = cameraService.getFacingModeForVideoTrack( videoTrack, @@ -723,10 +694,9 @@ void main() { 'the video track capabilities are not supported', ( WidgetTester tester, ) async { - mockVideoTrack.getSettings = - () { - return web.MediaTrackSettings(facingMode: ''); - }.toJS; + mockVideoTrack.getSettings = () { + return web.MediaTrackSettings(facingMode: ''); + }.toJS; when( jsUtil.hasProperty(videoTrack, 'getCapabilities'.toJS), diff --git a/packages/camera/camera_web/example/integration_test/camera_test.dart b/packages/camera/camera_web/example/integration_test/camera_test.dart index 280506bd394..69e0e55c8d3 100644 --- a/packages/camera/camera_web/example/integration_test/camera_test.dart +++ b/packages/camera/camera_web/example/integration_test/camera_test.dart @@ -323,12 +323,9 @@ void main() { videoElement = getVideoElementWithBlankStream(const Size(100, 100)) ..muted = true; - mockVideoTrack.getCapabilities = - () { - return MediaTrackCapabilities( - torch: [true.toJS].toJS, - ); - }.toJS; + mockVideoTrack.getCapabilities = () { + return MediaTrackCapabilities(torch: [true.toJS].toJS); + }.toJS; }); testWidgets('if the flash mode is auto', (WidgetTester tester) async { @@ -445,22 +442,19 @@ void main() { return Future.value().toJS; }.toJS; - mockVideoTrack.getCapabilities = - () { - return MediaTrackCapabilities(); - }.toJS; + mockVideoTrack.getCapabilities = () { + return MediaTrackCapabilities(); + }.toJS; }); testWidgets('sets the camera flash mode', (WidgetTester tester) async { - mockMediaDevices.getSupportedConstraints = - () { - return MediaTrackSupportedConstraints(torch: true); - }.toJS; + mockMediaDevices.getSupportedConstraints = () { + return MediaTrackSupportedConstraints(torch: true); + }.toJS; - mockVideoTrack.getCapabilities = - () { - return MediaTrackCapabilities(torch: [true.toJS].toJS); - }.toJS; + mockVideoTrack.getCapabilities = () { + return MediaTrackCapabilities(torch: [true.toJS].toJS); + }.toJS; final Camera camera = Camera(textureId: textureId, cameraService: cameraService) @@ -476,15 +470,13 @@ void main() { testWidgets('enables the torch mode ' 'if the flash mode is torch', (WidgetTester tester) async { - mockMediaDevices.getSupportedConstraints = - () { - return MediaTrackSupportedConstraints(torch: true); - }.toJS; + mockMediaDevices.getSupportedConstraints = () { + return MediaTrackSupportedConstraints(torch: true); + }.toJS; - mockVideoTrack.getCapabilities = - () { - return MediaTrackCapabilities(torch: [true.toJS].toJS); - }.toJS; + mockVideoTrack.getCapabilities = () { + return MediaTrackCapabilities(torch: [true.toJS].toJS); + }.toJS; final Camera camera = Camera(textureId: textureId, cameraService: cameraService) @@ -509,15 +501,13 @@ void main() { testWidgets('disables the torch mode ' 'if the flash mode is not torch', (WidgetTester tester) async { - mockMediaDevices.getSupportedConstraints = - () { - return MediaTrackSupportedConstraints(torch: true); - }.toJS; + mockMediaDevices.getSupportedConstraints = () { + return MediaTrackSupportedConstraints(torch: true); + }.toJS; - mockVideoTrack.getCapabilities = - () { - return MediaTrackCapabilities(torch: [true.toJS].toJS); - }.toJS; + mockVideoTrack.getCapabilities = () { + return MediaTrackCapabilities(torch: [true.toJS].toJS); + }.toJS; final Camera camera = Camera(textureId: textureId, cameraService: cameraService) @@ -544,17 +534,13 @@ void main() { testWidgets('with torchModeNotSupported error ' 'when the torch mode is not supported ' 'in the browser', (WidgetTester tester) async { - mockMediaDevices.getSupportedConstraints = - () { - return MediaTrackSupportedConstraints(torch: false); - }.toJS; + mockMediaDevices.getSupportedConstraints = () { + return MediaTrackSupportedConstraints(torch: false); + }.toJS; - mockVideoTrack.getCapabilities = - () { - return MediaTrackCapabilities( - torch: [true.toJS].toJS, - ); - }.toJS; + mockVideoTrack.getCapabilities = () { + return MediaTrackCapabilities(torch: [true.toJS].toJS); + }.toJS; final Camera camera = Camera(textureId: textureId, cameraService: cameraService) @@ -582,17 +568,13 @@ void main() { testWidgets('with torchModeNotSupported error ' 'when the torch mode is not supported ' 'by the camera', (WidgetTester tester) async { - mockMediaDevices.getSupportedConstraints = - () { - return MediaTrackSupportedConstraints(torch: true); - }.toJS; + mockMediaDevices.getSupportedConstraints = () { + return MediaTrackSupportedConstraints(torch: true); + }.toJS; - mockVideoTrack.getCapabilities = - () { - return MediaTrackCapabilities( - torch: [false.toJS].toJS, - ); - }.toJS; + mockVideoTrack.getCapabilities = () { + return MediaTrackCapabilities(torch: [false.toJS].toJS); + }.toJS; final Camera camera = Camera(textureId: textureId, cameraService: cameraService) @@ -621,17 +603,13 @@ void main() { 'when the camera stream has not been initialized', ( WidgetTester tester, ) async { - mockMediaDevices.getSupportedConstraints = - () { - return MediaTrackSupportedConstraints(torch: true); - }.toJS; + mockMediaDevices.getSupportedConstraints = () { + return MediaTrackSupportedConstraints(torch: true); + }.toJS; - mockVideoTrack.getCapabilities = - () { - return MediaTrackCapabilities( - torch: [true.toJS].toJS, - ); - }.toJS; + mockVideoTrack.getCapabilities = () { + return MediaTrackCapabilities(torch: [true.toJS].toJS); + }.toJS; final Camera camera = Camera( textureId: textureId, @@ -873,10 +851,9 @@ void main() { ) as MediaStream; - firstVideoTrack.getSettings = - () { - return MediaTrackSettings(facingMode: 'environment'); - }.toJS; + firstVideoTrack.getSettings = () { + return MediaTrackSettings(facingMode: 'environment'); + }.toJS; when( cameraService.mapFacingModeToLensDirection('environment'), @@ -910,10 +887,9 @@ void main() { ) as MediaStream; - firstVideoTrack.getSettings = - () { - return MediaTrackSettings(); - }.toJS; + firstVideoTrack.getSettings = () { + return MediaTrackSettings(); + }.toJS; expect(camera.getLensDirection(), isNull); }); @@ -1042,10 +1018,9 @@ void main() { await camera.play(); final List capturedStarts = []; - mockMediaRecorder.start = - ([int? timeslice]) { - capturedStarts.add(timeslice); - }.toJS; + mockMediaRecorder.start = ([int? timeslice]) { + capturedStarts.add(timeslice); + }.toJS; await camera.startVideoRecording(); @@ -1091,10 +1066,9 @@ void main() { )..mediaRecorder = mediaRecorder; int pauses = 0; - mockMediaRecorder.pause = - () { - pauses++; - }.toJS; + mockMediaRecorder.pause = () { + pauses++; + }.toJS; await camera.pauseVideoRecording(); @@ -1138,10 +1112,9 @@ void main() { )..mediaRecorder = mediaRecorder; int resumes = 0; - mockMediaRecorder.resume = - () { - resumes++; - }.toJS; + mockMediaRecorder.resume = () { + resumes++; + }.toJS; await camera.resumeVideoRecording(); @@ -1212,10 +1185,9 @@ void main() { await camera.startVideoRecording(); int stops = 0; - mockMediaRecorder.stop = - () { - stops++; - }.toJS; + mockMediaRecorder.stop = () { + stops++; + }.toJS; final Future videoFileFuture = camera.stopVideoRecording(); @@ -1528,8 +1500,9 @@ void main() { await camera.initialize(); - final List videoTracks = - camera.stream!.getVideoTracks().toDart; + final List videoTracks = camera.stream! + .getVideoTracks() + .toDart; final MediaStreamTrack defaultVideoTrack = videoTracks.first; defaultVideoTrack.dispatchEvent(Event('ended')); @@ -1551,8 +1524,9 @@ void main() { await camera.initialize(); - final List videoTracks = - camera.stream!.getVideoTracks().toDart; + final List videoTracks = camera.stream! + .getVideoTracks() + .toDart; final MediaStreamTrack defaultVideoTrack = videoTracks.first; camera.stop(); diff --git a/packages/camera/camera_web/example/integration_test/camera_web_test.dart b/packages/camera/camera_web/example/integration_test/camera_web_test.dart index ec619e27768..78e2f24dc5a 100644 --- a/packages/camera/camera_web/example/integration_test/camera_web_test.dart +++ b/packages/camera/camera_web/example/integration_test/camera_web_test.dart @@ -109,17 +109,16 @@ void main() { setUp(() { when(cameraService.getFacingModeForVideoTrack(any)).thenReturn(null); - mockMediaDevices.enumerateDevices = - () { - return Future>.value( - [].toJS, - ).toJS; - }.toJS; + mockMediaDevices.enumerateDevices = () { + return Future>.value( + [].toJS, + ).toJS; + }.toJS; }); testWidgets('requests video permissions', (WidgetTester tester) async { - final List _ = - await CameraPlatform.instance.availableCameras(); + final List _ = await CameraPlatform.instance + .availableCameras(); verify( cameraService.getMediaStreamForOptions(const CameraOptions()), @@ -133,10 +132,9 @@ void main() { createJSInteropWrapper(mockVideoTrack) as MediaStreamTrack; bool videoTrackStopped = false; - mockVideoTrack.stop = - () { - videoTrackStopped = true; - }.toJS; + mockVideoTrack.stop = () { + videoTrackStopped = true; + }.toJS; when( cameraService.getMediaStreamForOptions(const CameraOptions()), @@ -149,8 +147,8 @@ void main() { ), ); - final List _ = - await CameraPlatform.instance.availableCameras(); + final List _ = await CameraPlatform.instance + .availableCameras(); expect(videoTrackStopped, isTrue); }); @@ -167,15 +165,14 @@ void main() { ) as MediaDeviceInfo; - mockMediaDevices.enumerateDevices = - () { - return Future>.value( - [videoDevice].toJS, - ).toJS; - }.toJS; + mockMediaDevices.enumerateDevices = () { + return Future>.value( + [videoDevice].toJS, + ).toJS; + }.toJS; - final List _ = - await CameraPlatform.instance.availableCameras(); + final List _ = await CameraPlatform.instance + .availableCameras(); verify( cameraService.getMediaStreamForOptions( @@ -199,15 +196,14 @@ void main() { ) as MediaDeviceInfo; - mockMediaDevices.enumerateDevices = - () { - return Future>.value( - [videoDevice].toJS, - ).toJS; - }.toJS; + mockMediaDevices.enumerateDevices = () { + return Future>.value( + [videoDevice].toJS, + ).toJS; + }.toJS; - final List _ = - await CameraPlatform.instance.availableCameras(); + final List _ = await CameraPlatform.instance + .availableCameras(); verifyNever( cameraService.getMediaStreamForOptions( @@ -250,15 +246,14 @@ void main() { ), ).thenAnswer((_) => Future.value(videoStream)); - mockMediaDevices.enumerateDevices = - () { - return Future>.value( - [videoDevice].toJS, - ).toJS; - }.toJS; + mockMediaDevices.enumerateDevices = () { + return Future>.value( + [videoDevice].toJS, + ).toJS; + }.toJS; - final List _ = - await CameraPlatform.instance.availableCameras(); + final List _ = await CameraPlatform.instance + .availableCameras(); verify( cameraService.getFacingModeForVideoTrack( @@ -314,31 +309,30 @@ void main() { // Mock media devices to return two video input devices // and two audio devices. - mockMediaDevices.enumerateDevices = - () { - return Future>.value( - [ - firstVideoDevice, - createJSInteropWrapper( - FakeMediaDeviceInfo( - '2', - 'Audio Input 2', - MediaDeviceKind.audioInput, - ), - ) - as MediaDeviceInfo, - createJSInteropWrapper( - FakeMediaDeviceInfo( - '3', - 'Audio Output 3', - MediaDeviceKind.audioOutput, - ), - ) - as MediaDeviceInfo, - secondVideoDevice, - ].toJS, - ).toJS; - }.toJS; + mockMediaDevices.enumerateDevices = () { + return Future>.value( + [ + firstVideoDevice, + createJSInteropWrapper( + FakeMediaDeviceInfo( + '2', + 'Audio Input 2', + MediaDeviceKind.audioInput, + ), + ) + as MediaDeviceInfo, + createJSInteropWrapper( + FakeMediaDeviceInfo( + '3', + 'Audio Output 3', + MediaDeviceKind.audioOutput, + ), + ) + as MediaDeviceInfo, + secondVideoDevice, + ].toJS, + ).toJS; + }.toJS; // Mock camera service to return the first video stream // for the first video device. @@ -384,8 +378,8 @@ void main() { cameraService.mapFacingModeToLensDirection('environment'), ).thenReturn(CameraLensDirection.back); - final List cameras = - await CameraPlatform.instance.availableCameras(); + final List cameras = await CameraPlatform.instance + .availableCameras(); // Expect two cameras and ignore two audio devices. expect( @@ -428,12 +422,11 @@ void main() { ) as MediaStream; - mockMediaDevices.enumerateDevices = - () { - return Future>.value( - [videoDevice].toJS, - ).toJS; - }.toJS; + mockMediaDevices.enumerateDevices = () { + return Future>.value( + [videoDevice].toJS, + ).toJS; + }.toJS; when( cameraService.getMediaStreamForOptions( @@ -483,22 +476,20 @@ void main() { final List stops = List.generate(2, (_) => false); for (int i = 0; i < stops.length; i++) { final MockMediaStreamTrack track = MockMediaStreamTrack(); - track.stop = - () { - stops[i] = true; - }.toJS; + track.stop = () { + stops[i] = true; + }.toJS; tracks.add(createJSInteropWrapper(track) as MediaStreamTrack); } final MediaStream videoStream = createJSInteropWrapper(FakeMediaStream(tracks)) as MediaStream; - mockMediaDevices.enumerateDevices = - () { - return Future>.value( - [videoDevice].toJS, - ).toJS; - }.toJS; + mockMediaDevices.enumerateDevices = () { + return Future>.value( + [videoDevice].toJS, + ).toJS; + }.toJS; when( cameraService.getMediaStreamForOptions( @@ -508,8 +499,8 @@ void main() { ), ).thenAnswer((_) => Future.value(videoStream)); - final List _ = - await CameraPlatform.instance.availableCameras(); + final List _ = await CameraPlatform.instance + .availableCameras(); expect(stops.every((bool e) => e), isTrue); }); @@ -520,14 +511,13 @@ void main() { ) async { final DOMException exception = DOMException('UnknownError'); - mockMediaDevices.enumerateDevices = - () { - throw exception; - // ignore: dead_code - return Future>.value( - [].toJS, - ).toJS; - }.toJS; + mockMediaDevices.enumerateDevices = () { + throw exception; + // ignore: dead_code + return Future>.value( + [].toJS, + ).toJS; + }.toJS; expect( () => CameraPlatform.instance.availableCameras(), @@ -971,11 +961,10 @@ void main() { testWidgets('requests full-screen mode ' 'on documentElement', (WidgetTester tester) async { int fullscreenCalls = 0; - mockDocumentElement.requestFullscreen = - ([FullscreenOptions? options]) { - fullscreenCalls++; - return Future.value().toJS; - }.toJS; + mockDocumentElement.requestFullscreen = ([FullscreenOptions? options]) { + fullscreenCalls++; + return Future.value().toJS; + }.toJS; await CameraPlatform.instance.lockCaptureOrientation( cameraId, @@ -994,11 +983,10 @@ void main() { ).thenReturn(OrientationType.landscapeSecondary); final List capturedTypes = []; - mockScreenOrientation.lock = - (OrientationLockType orientation) { - capturedTypes.add(orientation); - return Future.value().toJS; - }.toJS; + mockScreenOrientation.lock = (OrientationLockType orientation) { + capturedTypes.add(orientation); + return Future.value().toJS; + }.toJS; await CameraPlatform.instance.lockCaptureOrientation( cameraId, @@ -1044,12 +1032,11 @@ void main() { ) async { final DOMException exception = DOMException('NotAllowedError'); - mockScreenOrientation.lock = - (OrientationLockType orientation) { - throw exception; - // ignore: dead_code - return Future.value().toJS; - }.toJS; + mockScreenOrientation.lock = (OrientationLockType orientation) { + throw exception; + // ignore: dead_code + return Future.value().toJS; + }.toJS; expect( () => CameraPlatform.instance.lockCaptureOrientation( @@ -1079,10 +1066,9 @@ void main() { WidgetTester tester, ) async { int unlocks = 0; - mockScreenOrientation.unlock = - () { - unlocks++; - }.toJS; + mockScreenOrientation.unlock = () { + unlocks++; + }.toJS; await CameraPlatform.instance.unlockCaptureOrientation(cameraId); @@ -1115,12 +1101,11 @@ void main() { ) async { final DOMException exception = DOMException('NotAllowedError'); - mockScreenOrientation.unlock = - () { - throw exception; - // ignore: dead_code - return Future.value().toJS; - }.toJS; + mockScreenOrientation.unlock = () { + throw exception; + // ignore: dead_code + return Future.value().toJS; + }.toJS; expect( () => CameraPlatform.instance.unlockCaptureOrientation(cameraId), @@ -3086,7 +3071,8 @@ void main() { final MockEventStreamProvider provider = MockEventStreamProvider(); (CameraPlatform.instance as CameraPlugin) - .orientationOnChangeProvider = provider; + .orientationOnChangeProvider = + provider; when( provider.forTarget(any), ).thenAnswer((_) => eventStreamController.stream); diff --git a/packages/camera/camera_web/example/integration_test/helpers/mocks.dart b/packages/camera/camera_web/example/integration_test/helpers/mocks.dart index 36634e9f7fc..5bb6d11dfb4 100644 --- a/packages/camera/camera_web/example/integration_test/helpers/mocks.dart +++ b/packages/camera/camera_web/example/integration_test/helpers/mocks.dart @@ -81,10 +81,9 @@ class MockScreen { @JSExport() class MockScreenOrientation { /// JSPromise Function(web.OrientationLockType orientation) - JSFunction lock = - (web.OrientationLockType orientation) { - return Future.value().toJS; - }.toJS; + JSFunction lock = (web.OrientationLockType orientation) { + return Future.value().toJS; + }.toJS; /// void Function() late JSFunction unlock; @@ -99,10 +98,9 @@ class MockDocument { @JSExport() class MockElement { /// JSPromise Function([FullscreenOptions options]) - JSFunction requestFullscreen = - ([web.FullscreenOptions? options]) { - return Future.value().toJS; - }.toJS; + JSFunction requestFullscreen = ([web.FullscreenOptions? options]) { + return Future.value().toJS; + }.toJS; } @JSExport() @@ -128,10 +126,9 @@ class MockMediaStreamTrack { late JSFunction getCapabilities; /// web.MediaTrackSettings Function() - JSFunction getSettings = - () { - return web.MediaTrackSettings(); - }.toJS; + JSFunction getSettings = () { + return web.MediaTrackSettings(); + }.toJS; /// JSPromise Function([web.MediaTrackConstraints? constraints]) late JSFunction applyConstraints; @@ -248,14 +245,13 @@ class FakeErrorEvent { /// final videoStream = videoElement.captureStream(); /// ``` web.HTMLVideoElement getVideoElementWithBlankStream(Size videoSize) { - final web.HTMLCanvasElement canvasElement = - web.HTMLCanvasElement() - ..width = videoSize.width.toInt() - ..height = videoSize.height.toInt() - ..context2D.fillRect(0, 0, videoSize.width, videoSize.height); - - final web.HTMLVideoElement videoElement = - web.HTMLVideoElement()..srcObject = canvasElement.captureStream(); + final web.HTMLCanvasElement canvasElement = web.HTMLCanvasElement() + ..width = videoSize.width.toInt() + ..height = videoSize.height.toInt() + ..context2D.fillRect(0, 0, videoSize.width, videoSize.height); + + final web.HTMLVideoElement videoElement = web.HTMLVideoElement() + ..srcObject = canvasElement.captureStream(); return videoElement; } diff --git a/packages/camera/camera_web/example/pubspec.yaml b/packages/camera/camera_web/example/pubspec.yaml index d9f9854bc1f..fff2e4ce9d6 100644 --- a/packages/camera/camera_web/example/pubspec.yaml +++ b/packages/camera/camera_web/example/pubspec.yaml @@ -2,8 +2,8 @@ name: camera_web_integration_tests publish_to: none environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: camera_platform_interface: ^2.6.0 diff --git a/packages/camera/camera_web/lib/src/camera.dart b/packages/camera/camera_web/lib/src/camera.dart index f23c9e56742..e5926a78d94 100644 --- a/packages/camera/camera_web/lib/src/camera.dart +++ b/packages/camera/camera_web/lib/src/camera.dart @@ -129,8 +129,8 @@ class Camera { /// Whether the video of the given type is supported. @visibleForTesting - bool Function(String) isVideoTypeSupported = - (String type) => web.MediaRecorder.isTypeSupported(type); + bool Function(String) isVideoTypeSupported = (String type) => + web.MediaRecorder.isTypeSupported(type); /// The list of consecutive video data files recorded with [mediaRecorder]. final List _videoData = []; @@ -170,12 +170,11 @@ class Camera { videoElement = web.HTMLVideoElement(); - divElement = - web.HTMLDivElement() - ..style.setProperty('object-fit', 'cover') - ..style.setProperty('height', '100%') - ..style.setProperty('width', '100%') - ..append(videoElement); + divElement = web.HTMLDivElement() + ..style.setProperty('object-fit', 'cover') + ..style.setProperty('height', '100%') + ..style.setProperty('width', '100%') + ..append(videoElement); ui_web.platformViewRegistry.registerViewFactory( _getViewType(textureId), @@ -190,8 +189,9 @@ class Camera { _applyDefaultVideoStyles(videoElement); - final List videoTracks = - stream!.getVideoTracks().toDart; + final List videoTracks = stream! + .getVideoTracks() + .toDart; if (videoTracks.isNotEmpty) { final web.MediaStreamTrack defaultVideoTrack = videoTracks.first; @@ -224,8 +224,9 @@ class Camera { /// Stops the camera stream and resets the camera source. void stop() { - final List videoTracks = - stream!.getVideoTracks().toDart; + final List videoTracks = stream! + .getVideoTracks() + .toDart; if (videoTracks.isNotEmpty) { onEndedController.add(videoTracks.first); } @@ -254,10 +255,9 @@ class Camera { final int videoWidth = videoElement.videoWidth; final int videoHeight = videoElement.videoHeight; - final web.HTMLCanvasElement canvas = - web.HTMLCanvasElement() - ..width = videoWidth - ..height = videoHeight; + final web.HTMLCanvasElement canvas = web.HTMLCanvasElement() + ..width = videoWidth + ..height = videoHeight; final bool isBackCamera = getLensDirection() == CameraLensDirection.back; // Flip the picture horizontally if it is not taken from a back camera. @@ -306,8 +306,8 @@ class Camera { final web.MediaStreamTrack defaultVideoTrack = videoTracks.first; - final web.MediaTrackSettings defaultVideoTrackSettings = - defaultVideoTrack.getSettings(); + final web.MediaTrackSettings defaultVideoTrackSettings = defaultVideoTrack + .getSettings(); final int width = defaultVideoTrackSettings.width; final int height = defaultVideoTrackSettings.height; @@ -328,8 +328,8 @@ class Camera { /// or the camera has not been initialized or started. void setFlashMode(FlashMode mode) { final web.MediaDevices mediaDevices = window.navigator.mediaDevices; - final web.MediaTrackSupportedConstraints supportedConstraints = - mediaDevices.getSupportedConstraints(); + final web.MediaTrackSupportedConstraints supportedConstraints = mediaDevices + .getSupportedConstraints(); final bool torchModeSupported = supportedConstraints.torchNullable ?? false; if (!torchModeSupported) { @@ -436,8 +436,8 @@ class Camera { } final web.MediaStreamTrack defaultVideoTrack = videoTracks.first; - final web.MediaTrackSettings defaultVideoTrackSettings = - defaultVideoTrack.getSettings(); + final web.MediaTrackSettings defaultVideoTrackSettings = defaultVideoTrack + .getSettings(); final String? facingMode = defaultVideoTrackSettings.facingModeNullable; @@ -473,11 +473,11 @@ class Camera { _videoAvailableCompleter = Completer(); - _videoDataAvailableListener = - (web.BlobEvent event) => _onVideoDataAvailable(event); + _videoDataAvailableListener = (web.BlobEvent event) => + _onVideoDataAvailable(event); - _videoRecordingStoppedListener = - (web.Event event) => _onVideoRecordingStopped(event); + _videoRecordingStoppedListener = (web.Event event) => + _onVideoRecordingStopped(event); mediaRecorder!.addEventListener( 'dataavailable', @@ -613,13 +613,11 @@ class Camera { return types.firstWhere( (String type) => isVideoTypeSupported(type), - orElse: - () => - throw CameraWebException( - textureId, - CameraErrorCode.notSupported, - 'The browser does not support any of the following video types: ${types.join(',')}.', - ), + orElse: () => throw CameraWebException( + textureId, + CameraErrorCode.notSupported, + 'The browser does not support any of the following video types: ${types.join(',')}.', + ), ); } diff --git a/packages/camera/camera_web/lib/src/camera_service.dart b/packages/camera/camera_web/lib/src/camera_service.dart index 1f1341bd286..828f5391481 100644 --- a/packages/camera/camera_web/lib/src/camera_service.dart +++ b/packages/camera/camera_web/lib/src/camera_service.dart @@ -110,8 +110,8 @@ class CameraService { /// or the camera has not been initialized or started. ZoomLevelCapability getZoomLevelCapabilityForCamera(Camera camera) { final web.MediaDevices mediaDevices = window.navigator.mediaDevices; - final web.MediaTrackSupportedConstraints supportedConstraints = - mediaDevices.getSupportedConstraints(); + final web.MediaTrackSupportedConstraints supportedConstraints = mediaDevices + .getSupportedConstraints(); final bool zoomLevelSupported = supportedConstraints.zoomNullable ?? false; if (!zoomLevelSupported) { @@ -130,8 +130,9 @@ class CameraService { /// The zoom level capability is represented by MediaSettingsRange. /// See: https://developer.mozilla.org/en-US/docs/Web/API/MediaSettingsRange - final WebTweakMediaSettingsRange? zoomLevelCapability = - defaultVideoTrack.getCapabilities().zoomNullable; + final WebTweakMediaSettingsRange? zoomLevelCapability = defaultVideoTrack + .getCapabilities() + .zoomNullable; if (zoomLevelCapability != null) { return ZoomLevelCapability( @@ -161,8 +162,8 @@ class CameraService { final web.MediaDevices mediaDevices = window.navigator.mediaDevices; // Check if the camera facing mode is supported by the current browser. - final web.MediaTrackSupportedConstraints supportedConstraints = - mediaDevices.getSupportedConstraints(); + final web.MediaTrackSupportedConstraints supportedConstraints = mediaDevices + .getSupportedConstraints(); // Return null if the facing mode is not supported. if (!supportedConstraints.facingMode) { @@ -194,15 +195,16 @@ class CameraService { return null; } - final web.MediaTrackCapabilities videoTrackCapabilities = - videoTrack.getCapabilities(); + final web.MediaTrackCapabilities videoTrackCapabilities = videoTrack + .getCapabilities(); // A list of facing mode capabilities as // the camera may support multiple facing modes. - final List facingModeCapabilities = - videoTrackCapabilities.facingMode.toDart - .map((JSString e) => e.toDart) - .toList(); + final List facingModeCapabilities = videoTrackCapabilities + .facingMode + .toDart + .map((JSString e) => e.toDart) + .toList(); if (facingModeCapabilities.isNotEmpty) { final String facingModeCapability = facingModeCapabilities.first; diff --git a/packages/camera/camera_web/lib/src/camera_web.dart b/packages/camera/camera_web/lib/src/camera_web.dart index 5feffa969ef..2210a4ecba2 100644 --- a/packages/camera/camera_web/lib/src/camera_web.dart +++ b/packages/camera/camera_web/lib/src/camera_web.dart @@ -134,8 +134,9 @@ class CameraPlugin extends CameraPlatform { // Get all video tracks in the video stream // to later extract the lens direction from the first track. - final List videoTracks = - videoStream.getVideoTracks().toDart; + final List videoTracks = videoStream + .getVideoTracks() + .toDart; if (videoTracks.isNotEmpty) { // Get the facing mode from the first available video track. @@ -146,10 +147,9 @@ class CameraPlugin extends CameraPlatform { // Get the lens direction based on the facing mode. // Fallback to the external lens direction // if the facing mode is not available. - final CameraLensDirection lensDirection = - facingMode != null - ? _cameraService.mapFacingModeToLensDirection(facingMode) - : CameraLensDirection.external; + final CameraLensDirection lensDirection = facingMode != null + ? _cameraService.mapFacingModeToLensDirection(facingMode) + : CameraLensDirection.external; // Create a camera description. // @@ -224,12 +224,9 @@ class CameraPlugin extends CameraPlatform { final CameraMetadata cameraMetadata = camerasMetadata[cameraDescription]!; - final CameraType? cameraType = - cameraMetadata.facingMode != null - ? _cameraService.mapFacingModeToCameraType( - cameraMetadata.facingMode!, - ) - : null; + final CameraType? cameraType = cameraMetadata.facingMode != null + ? _cameraService.mapFacingModeToCameraType(cameraMetadata.facingMode!) + : null; // Use the highest resolution possible // if the resolution preset is not specified. @@ -245,8 +242,9 @@ class CameraPlugin extends CameraPlatform { options: CameraOptions( audio: AudioConstraints(enabled: mediaSettings?.enableAudio ?? true), video: VideoConstraints( - facingMode: - cameraType != null ? FacingModeConstraint(cameraType) : null, + facingMode: cameraType != null + ? FacingModeConstraint(cameraType) + : null, width: VideoSizeConstraint(ideal: videoSize.width.toInt()), height: VideoSizeConstraint(ideal: videoSize.height.toInt()), deviceId: cameraMetadata.deviceId, @@ -289,8 +287,9 @@ class CameraPlugin extends CameraPlatform { final CameraErrorCode errorCode = CameraErrorCode.fromMediaError( error, ); - final String errorMessage = - error.message != '' ? error.message : _kDefaultErrorMessage; + final String errorMessage = error.message != '' + ? error.message + : _kDefaultErrorMessage; cameraEventStreamController.add( CameraErrorEvent( @@ -503,8 +502,9 @@ class CameraPlugin extends CameraPlatform { @override Future stopVideoRecording(int cameraId) async { try { - final XFile videoRecording = - await getCamera(cameraId).stopVideoRecording(); + final XFile videoRecording = await getCamera( + cameraId, + ).stopVideoRecording(); await _cameraVideoRecordingErrorSubscriptions[cameraId]?.cancel(); return videoRecording; } on web.DOMException catch (e) { diff --git a/packages/camera/camera_web/pubspec.yaml b/packages/camera/camera_web/pubspec.yaml index c32cfb084b0..045022e9405 100644 --- a/packages/camera/camera_web/pubspec.yaml +++ b/packages/camera/camera_web/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 0.3.5 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" flutter: plugin: diff --git a/packages/camera/camera_windows/CHANGELOG.md b/packages/camera/camera_windows/CHANGELOG.md index 9a001ea738d..094a52d93b8 100644 --- a/packages/camera/camera_windows/CHANGELOG.md +++ b/packages/camera/camera_windows/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 0.2.6+2 diff --git a/packages/camera/camera_windows/example/integration_test/camera_test.dart b/packages/camera/camera_windows/example/integration_test/camera_test.dart index 290ff0f9ad1..03b791503c5 100644 --- a/packages/camera/camera_windows/example/integration_test/camera_test.dart +++ b/packages/camera/camera_windows/example/integration_test/camera_test.dart @@ -100,8 +100,9 @@ void main() { testWidgets('emits the initial DeviceOrientationChangedEvent', ( WidgetTester _, ) async { - final Stream eventStream = - CameraPlatform.instance.onDeviceOrientationChanged(); + final Stream eventStream = CameraPlatform + .instance + .onDeviceOrientationChanged(); final StreamQueue streamQueue = StreamQueue(eventStream); diff --git a/packages/camera/camera_windows/example/lib/main.dart b/packages/camera/camera_windows/example/lib/main.dart index 8a1e7215bd6..6745bcbdd6d 100644 --- a/packages/camera/camera_windows/example/lib/main.dart +++ b/packages/camera/camera_windows/example/lib/main.dart @@ -113,8 +113,9 @@ class _MyAppState extends State { .onCameraClosing(cameraId) .listen(_onCameraClosing); - final Future initialized = - CameraPlatform.instance.onCameraInitialized(cameraId).first; + final Future initialized = CameraPlatform.instance + .onCameraInitialized(cameraId) + .first; await CameraPlatform.instance.initializeCamera(cameraId); @@ -384,10 +385,9 @@ class _MyAppState extends State { ), const SizedBox(width: 20), ElevatedButton( - onPressed: - _initialized - ? _disposeCurrentCamera - : _initializeCamera, + onPressed: _initialized + ? _disposeCurrentCamera + : _initializeCamera, child: Text( _initialized ? 'Dispose camera' : 'Create camera', ), @@ -415,10 +415,9 @@ class _MyAppState extends State { ), const SizedBox(width: 5), ElevatedButton( - onPressed: - (_initialized && !_recording && !_recordingTimed) - ? () => _recordTimed(5) - : null, + onPressed: (_initialized && !_recording && !_recordingTimed) + ? () => _recordTimed(5) + : null, child: const Text('Record 5 seconds'), ), if (_cameras.length > 1) ...[ diff --git a/packages/camera/camera_windows/example/pubspec.yaml b/packages/camera/camera_windows/example/pubspec.yaml index 26b1e43bfa6..87ede11c4bc 100644 --- a/packages/camera/camera_windows/example/pubspec.yaml +++ b/packages/camera/camera_windows/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the camera_windows plugin. publish_to: 'none' environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: camera_platform_interface: ^2.6.0 diff --git a/packages/camera/camera_windows/lib/src/messages.g.dart b/packages/camera/camera_windows/lib/src/messages.g.dart index 6a96efa118d..c21a1386dd6 100644 --- a/packages/camera/camera_windows/lib/src/messages.g.dart +++ b/packages/camera/camera_windows/lib/src/messages.g.dart @@ -143,8 +143,9 @@ class CameraApi { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -419,8 +420,9 @@ abstract class CameraEventApi { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) { - messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; { final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( diff --git a/packages/camera/camera_windows/pubspec.yaml b/packages/camera/camera_windows/pubspec.yaml index d064fa093a0..8698512c5e4 100644 --- a/packages/camera/camera_windows/pubspec.yaml +++ b/packages/camera/camera_windows/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 0.2.6+2 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" flutter: plugin: diff --git a/packages/camera/camera_windows/test/camera_windows_test.dart b/packages/camera/camera_windows/test/camera_windows_test.dart index 172f105b739..a3b0e0e98ab 100644 --- a/packages/camera/camera_windows/test/camera_windows_test.dart +++ b/packages/camera/camera_windows/test/camera_windows_test.dart @@ -315,8 +315,8 @@ void main() { ).thenAnswer((_) async => returnData); // Act - final List cameras = - await plugin.availableCameras(); + final List cameras = await plugin + .availableCameras(); // Assert expect(cameras.length, returnData.length); diff --git a/packages/cross_file/CHANGELOG.md b/packages/cross_file/CHANGELOG.md index 164a5650194..5f384d70580 100644 --- a/packages/cross_file/CHANGELOG.md +++ b/packages/cross_file/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. + ## 0.3.5 * Fixes a bug where the bytes of an XFile, that is created using the `XFile.fromData` constructor, are ignored on web. diff --git a/packages/cross_file/example/pubspec.yaml b/packages/cross_file/example/pubspec.yaml index 8bb5355bdec..aec48e35e3c 100644 --- a/packages/cross_file/example/pubspec.yaml +++ b/packages/cross_file/example/pubspec.yaml @@ -3,7 +3,7 @@ description: Demonstrates how to use cross files. publish_to: none environment: - sdk: ^3.7.0 + sdk: ^3.8.0 dependencies: cross_file: diff --git a/packages/cross_file/lib/src/types/html.dart b/packages/cross_file/lib/src/types/html.dart index 33e937b59bf..a8047e6a926 100644 --- a/packages/cross_file/lib/src/types/html.dart +++ b/packages/cross_file/lib/src/types/html.dart @@ -73,9 +73,9 @@ class XFile extends XFileBase { return (mimeType == null) ? Blob([bytes.toJS].toJS) : Blob( - [bytes.toJS].toJS, - BlobPropertyBag(type: mimeType), - ); + [bytes.toJS].toJS, + BlobPropertyBag(type: mimeType), + ); } // Overridable (meta) data that can be specified by the constructors. @@ -134,27 +134,24 @@ class XFile extends XFileBase { final Completer blobCompleter = Completer(); late XMLHttpRequest request; - request = - XMLHttpRequest() - ..open('get', path, true) - ..responseType = 'blob' - ..onLoad.listen((ProgressEvent e) { - assert( - request.response != null, - 'The Blob backing this XFile cannot be null!', - ); - blobCompleter.complete(request.response! as Blob); - }) - ..onError.listen((ProgressEvent e) { - if (e.type == 'error') { - blobCompleter.completeError( - Exception( - 'Could not load Blob from its URL. Has it been revoked?', - ), - ); - } - }) - ..send(); + request = XMLHttpRequest() + ..open('get', path, true) + ..responseType = 'blob' + ..onLoad.listen((ProgressEvent e) { + assert( + request.response != null, + 'The Blob backing this XFile cannot be null!', + ); + blobCompleter.complete(request.response! as Blob); + }) + ..onError.listen((ProgressEvent e) { + if (e.type == 'error') { + blobCompleter.completeError( + Exception('Could not load Blob from its URL. Has it been revoked?'), + ); + } + }) + ..send(); return blobCompleter.future; } @@ -191,8 +188,8 @@ class XFile extends XFileBase { await reader.onLoadEnd.first; - final Uint8List? result = - (reader.result as JSArrayBuffer?)?.toDart.asUint8List(); + final Uint8List? result = (reader.result as JSArrayBuffer?)?.toDart + .asUint8List(); if (result == null) { throw Exception('Cannot read bytes from Blob. Is it still available?'); @@ -212,11 +209,9 @@ class XFile extends XFileBase { // Create an tag with the appropriate download attributes and click it // May be overridden with CrossFileTestOverrides - final HTMLAnchorElement element = - _hasTestOverrides - ? _overrides!.createAnchorElement(this.path, name) - as HTMLAnchorElement - : createAnchorElement(this.path, name); + final HTMLAnchorElement element = _hasTestOverrides + ? _overrides!.createAnchorElement(this.path, name) as HTMLAnchorElement + : createAnchorElement(this.path, name); // Clear the children in _target and add an element to click while (_target.children.length > 0) { diff --git a/packages/cross_file/pubspec.yaml b/packages/cross_file/pubspec.yaml index 5be291469c2..8b05c8bf69a 100644 --- a/packages/cross_file/pubspec.yaml +++ b/packages/cross_file/pubspec.yaml @@ -5,7 +5,7 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 0.3.5 environment: - sdk: ^3.7.0 + sdk: ^3.8.0 dependencies: meta: ^1.3.0 diff --git a/packages/cross_file/test/x_file_html_test.dart b/packages/cross_file/test/x_file_html_test.dart index cd938be1e70..f71f1271829 100644 --- a/packages/cross_file/test/x_file_html_test.dart +++ b/packages/cross_file/test/x_file_html_test.dart @@ -20,9 +20,9 @@ final html.File textFile = html.File( 'hello.txt', ); final String textFileUrl = -// TODO(kevmoo): drop ignore when pkg:web constraint excludes v0.3 -// ignore: unnecessary_cast -html.URL.createObjectURL(textFile as JSObject); + // TODO(kevmoo): drop ignore when pkg:web constraint excludes v0.3 + // ignore: unnecessary_cast + html.URL.createObjectURL(textFile as JSObject); void main() { group('Create with an objectUrl', () { @@ -88,8 +88,9 @@ void main() { test('Stores data as a Blob', () async { // Read the blob from its path 'natively' - final html.Response response = - await html.window.fetch(file.path.toJS).toDart; + final html.Response response = await html.window + .fetch(file.path.toJS) + .toDart; final JSAny arrayBuffer = await response.arrayBuffer().toDart; final ByteBuffer data = (arrayBuffer as JSArrayBuffer).toDart; @@ -126,8 +127,9 @@ void main() { await file.saveTo('path'); - final html.Element container = - html.document.querySelector('#$crossFileDomElementId')!; + final html.Element container = html.document.querySelector( + '#$crossFileDomElementId', + )!; late html.HTMLAnchorElement element; for (int i = 0; i < container.childNodes.length; i++) { diff --git a/packages/cross_file/test/x_file_io_test.dart b/packages/cross_file/test/x_file_io_test.dart index a6de36568d1..56a3b8cb9cc 100644 --- a/packages/cross_file/test/x_file_io_test.dart +++ b/packages/cross_file/test/x_file_io_test.dart @@ -12,8 +12,9 @@ import 'dart:typed_data'; import 'package:cross_file/cross_file.dart'; import 'package:test/test.dart'; -final String pathPrefix = - Directory.current.path.endsWith('test') ? './assets/' : './test/assets/'; +final String pathPrefix = Directory.current.path.endsWith('test') + ? './assets/' + : './test/assets/'; final String path = '${pathPrefix}hello.txt'; const String expectedStringContents = 'Hello, world!'; final Uint8List bytes = Uint8List.fromList(utf8.encode(expectedStringContents)); diff --git a/packages/espresso/CHANGELOG.md b/packages/espresso/CHANGELOG.md index 21857bb3473..2bffe18705a 100644 --- a/packages/espresso/CHANGELOG.md +++ b/packages/espresso/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. + ## 0.4.0+18 * Bumps `com.squareup.okhttp3:okhttp` from 5.1.0 to 5.3.0. diff --git a/packages/espresso/example/pubspec.yaml b/packages/espresso/example/pubspec.yaml index 85d482f4eb2..895750e7aae 100644 --- a/packages/espresso/example/pubspec.yaml +++ b/packages/espresso/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the espresso plugin. publish_to: none environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/extension_google_sign_in_as_googleapis_auth/CHANGELOG.md b/packages/extension_google_sign_in_as_googleapis_auth/CHANGELOG.md index 13720c1e0c9..f9a3e0cb4a8 100644 --- a/packages/extension_google_sign_in_as_googleapis_auth/CHANGELOG.md +++ b/packages/extension_google_sign_in_as_googleapis_auth/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 3.0.0 diff --git a/packages/extension_google_sign_in_as_googleapis_auth/example/pubspec.yaml b/packages/extension_google_sign_in_as_googleapis_auth/example/pubspec.yaml index 8a297916798..899a737ebcf 100644 --- a/packages/extension_google_sign_in_as_googleapis_auth/example/pubspec.yaml +++ b/packages/extension_google_sign_in_as_googleapis_auth/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Example of Google Sign-In plugin and googleapis. publish_to: none environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: extension_google_sign_in_as_googleapis_auth: diff --git a/packages/extension_google_sign_in_as_googleapis_auth/pubspec.yaml b/packages/extension_google_sign_in_as_googleapis_auth/pubspec.yaml index c36b2a630e2..4bfe1010eeb 100644 --- a/packages/extension_google_sign_in_as_googleapis_auth/pubspec.yaml +++ b/packages/extension_google_sign_in_as_googleapis_auth/pubspec.yaml @@ -11,8 +11,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 3.0.0 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/file_selector/file_selector/CHANGELOG.md b/packages/file_selector/file_selector/CHANGELOG.md index 16122ff93c0..189d99c9634 100644 --- a/packages/file_selector/file_selector/CHANGELOG.md +++ b/packages/file_selector/file_selector/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. + ## 1.0.4 * Updates the example app and README examples to work on iOS. diff --git a/packages/file_selector/file_selector/example/lib/home_page.dart b/packages/file_selector/file_selector/example/lib/home_page.dart index b059580ad85..76801d5fa58 100644 --- a/packages/file_selector/file_selector/example/lib/home_page.dart +++ b/packages/file_selector/file_selector/example/lib/home_page.dart @@ -64,8 +64,8 @@ class HomePage extends StatelessWidget { ElevatedButton( style: style, child: const Text('Open a get multi directories dialog'), - onPressed: - () => Navigator.pushNamed(context, '/multi-directories'), + onPressed: () => + Navigator.pushNamed(context, '/multi-directories'), ), ], ], diff --git a/packages/file_selector/file_selector/example/lib/main.dart b/packages/file_selector/file_selector/example/lib/main.dart index a2810d08c42..da38163967d 100644 --- a/packages/file_selector/file_selector/example/lib/main.dart +++ b/packages/file_selector/file_selector/example/lib/main.dart @@ -32,13 +32,13 @@ class MyApp extends StatelessWidget { home: const HomePage(), routes: { '/open/image': (BuildContext context) => const OpenImagePage(), - '/open/images': - (BuildContext context) => const OpenMultipleImagesPage(), + '/open/images': (BuildContext context) => + const OpenMultipleImagesPage(), '/open/text': (BuildContext context) => const OpenTextPage(), '/save/text': (BuildContext context) => SaveTextPage(), '/directory': (BuildContext context) => GetDirectoryPage(), - '/multi-directories': - (BuildContext context) => const GetMultipleDirectoriesPage(), + '/multi-directories': (BuildContext context) => + const GetMultipleDirectoriesPage(), }, ); } diff --git a/packages/file_selector/file_selector/example/lib/open_multiple_images_page.dart b/packages/file_selector/file_selector/example/lib/open_multiple_images_page.dart index a1fd347cc1e..9f74c92f5af 100644 --- a/packages/file_selector/file_selector/example/lib/open_multiple_images_page.dart +++ b/packages/file_selector/file_selector/example/lib/open_multiple_images_page.dart @@ -83,10 +83,9 @@ class MultipleImagesDisplay extends StatelessWidget { children: [ ...files.map( (XFile file) => Flexible( - child: - kIsWeb - ? Image.network(file.path) - : Image.file(File(file.path)), + child: kIsWeb + ? Image.network(file.path) + : Image.file(File(file.path)), ), ), ], diff --git a/packages/file_selector/file_selector/example/lib/open_text_page.dart b/packages/file_selector/file_selector/example/lib/open_text_page.dart index de751fe1196..55ea3ff7d69 100644 --- a/packages/file_selector/file_selector/example/lib/open_text_page.dart +++ b/packages/file_selector/file_selector/example/lib/open_text_page.dart @@ -21,8 +21,9 @@ class OpenTextPage extends StatelessWidget { // This demonstrates using an initial directory for the prompt, which should // only be done in cases where the application can likely predict where the // file would be. In most cases, this parameter should not be provided. - final String? initialDirectory = - kIsWeb ? null : (await getApplicationDocumentsDirectory()).path; + final String? initialDirectory = kIsWeb + ? null + : (await getApplicationDocumentsDirectory()).path; final XFile? file = await openFile( acceptedTypeGroups: [typeGroup], initialDirectory: initialDirectory, diff --git a/packages/file_selector/file_selector/example/lib/save_text_page.dart b/packages/file_selector/file_selector/example/lib/save_text_page.dart index 0c8d825048b..d5dcd117458 100644 --- a/packages/file_selector/file_selector/example/lib/save_text_page.dart +++ b/packages/file_selector/file_selector/example/lib/save_text_page.dart @@ -23,10 +23,9 @@ class SaveTextPage extends StatelessWidget { // only be done in cases where the application can likely predict where the // file will be saved. In most cases, this parameter should not be provided, // and in the web, path_provider shouldn't even be called. - final String? initialDirectory = - kIsWeb - ? null - : (await path_provider.getApplicationDocumentsDirectory()).path; + final String? initialDirectory = kIsWeb + ? null + : (await path_provider.getApplicationDocumentsDirectory()).path; final FileSaveLocation? result = await getSaveLocation( initialDirectory: initialDirectory, suggestedName: fileName, diff --git a/packages/file_selector/file_selector/example/pubspec.yaml b/packages/file_selector/file_selector/example/pubspec.yaml index bd8a1c0881b..34989cd991a 100644 --- a/packages/file_selector/file_selector/example/pubspec.yaml +++ b/packages/file_selector/file_selector/example/pubspec.yaml @@ -5,8 +5,8 @@ publish_to: none version: 1.0.0+1 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: file_selector: diff --git a/packages/file_selector/file_selector/pubspec.yaml b/packages/file_selector/file_selector/pubspec.yaml index b3db183febe..5a8c457a1e8 100644 --- a/packages/file_selector/file_selector/pubspec.yaml +++ b/packages/file_selector/file_selector/pubspec.yaml @@ -6,8 +6,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 1.0.4 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" flutter: plugin: diff --git a/packages/file_selector/file_selector/test/file_selector_test.dart b/packages/file_selector/file_selector/test/file_selector_test.dart index 6cadab026bf..9320ceb0db2 100644 --- a/packages/file_selector/file_selector/test/file_selector_test.dart +++ b/packages/file_selector/file_selector/test/file_selector_test.dart @@ -424,12 +424,11 @@ class FakeFileSelector extends Fake return path == null ? null : FileSaveLocation( - path, - activeFilter: - activeFilterIndex == null - ? null - : acceptedTypeGroups?[activeFilterIndex], - ); + path, + activeFilter: activeFilterIndex == null + ? null + : acceptedTypeGroups?[activeFilterIndex], + ); } @override diff --git a/packages/file_selector/file_selector_android/CHANGELOG.md b/packages/file_selector/file_selector_android/CHANGELOG.md index d72506f8d21..59e20b8b019 100644 --- a/packages/file_selector/file_selector_android/CHANGELOG.md +++ b/packages/file_selector/file_selector_android/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. + ## 0.5.2+2 * Removed mockito-inline and updated to mockito-core 5.17.0. diff --git a/packages/file_selector/file_selector_android/example/lib/main.dart b/packages/file_selector/file_selector_android/example/lib/main.dart index 1a2362dc1e1..b69b4c1e4e9 100644 --- a/packages/file_selector/file_selector_android/example/lib/main.dart +++ b/packages/file_selector/file_selector_android/example/lib/main.dart @@ -40,8 +40,8 @@ class MyApp extends StatelessWidget { home: const HomePage(), routes: { '/open/image': (BuildContext context) => const OpenImagePage(), - '/open/images': - (BuildContext context) => const OpenMultipleImagesPage(), + '/open/images': (BuildContext context) => + const OpenMultipleImagesPage(), '/open/text': (BuildContext context) => const OpenTextPage(), }, ); diff --git a/packages/file_selector/file_selector_android/example/pubspec.yaml b/packages/file_selector/file_selector_android/example/pubspec.yaml index 8b7074557c2..52f274b2edf 100644 --- a/packages/file_selector/file_selector_android/example/pubspec.yaml +++ b/packages/file_selector/file_selector_android/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the file_selector_android plugin. publish_to: 'none' environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: file_selector_android: diff --git a/packages/file_selector/file_selector_linux/CHANGELOG.md b/packages/file_selector/file_selector_linux/CHANGELOG.md index bcff55dae5a..1c0b1fc62c1 100644 --- a/packages/file_selector/file_selector_linux/CHANGELOG.md +++ b/packages/file_selector/file_selector_linux/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 0.9.3+2 diff --git a/packages/file_selector/file_selector_linux/example/lib/get_multiple_directories_page.dart b/packages/file_selector/file_selector_linux/example/lib/get_multiple_directories_page.dart index 0c5297313d2..fe7fd3d2416 100644 --- a/packages/file_selector/file_selector_linux/example/lib/get_multiple_directories_page.dart +++ b/packages/file_selector/file_selector_linux/example/lib/get_multiple_directories_page.dart @@ -22,8 +22,8 @@ class GetMultipleDirectoriesPage extends StatelessWidget { if (context.mounted) { await showDialog( context: context, - builder: - (BuildContext context) => TextDisplay(directoryPaths.join('\n')), + builder: (BuildContext context) => + TextDisplay(directoryPaths.join('\n')), ); } } diff --git a/packages/file_selector/file_selector_linux/example/lib/home_page.dart b/packages/file_selector/file_selector_linux/example/lib/home_page.dart index a4e6f828876..b49884852ba 100644 --- a/packages/file_selector/file_selector_linux/example/lib/home_page.dart +++ b/packages/file_selector/file_selector_linux/example/lib/home_page.dart @@ -54,8 +54,8 @@ class HomePage extends StatelessWidget { ElevatedButton( style: style, child: const Text('Open a get directories dialog'), - onPressed: - () => Navigator.pushNamed(context, '/multi-directories'), + onPressed: () => + Navigator.pushNamed(context, '/multi-directories'), ), ], ), diff --git a/packages/file_selector/file_selector_linux/example/lib/main.dart b/packages/file_selector/file_selector_linux/example/lib/main.dart index f1d207839e6..28a34200274 100644 --- a/packages/file_selector/file_selector_linux/example/lib/main.dart +++ b/packages/file_selector/file_selector_linux/example/lib/main.dart @@ -32,13 +32,13 @@ class MyApp extends StatelessWidget { home: const HomePage(), routes: { '/open/image': (BuildContext context) => const OpenImagePage(), - '/open/images': - (BuildContext context) => const OpenMultipleImagesPage(), + '/open/images': (BuildContext context) => + const OpenMultipleImagesPage(), '/open/text': (BuildContext context) => const OpenTextPage(), '/save/text': (BuildContext context) => SaveTextPage(), '/directory': (BuildContext context) => const GetDirectoryPage(), - '/multi-directories': - (BuildContext context) => const GetMultipleDirectoriesPage(), + '/multi-directories': (BuildContext context) => + const GetMultipleDirectoriesPage(), }, ); } diff --git a/packages/file_selector/file_selector_linux/example/lib/open_multiple_images_page.dart b/packages/file_selector/file_selector_linux/example/lib/open_multiple_images_page.dart index 1b11e49391f..0b9fe352516 100644 --- a/packages/file_selector/file_selector_linux/example/lib/open_multiple_images_page.dart +++ b/packages/file_selector/file_selector_linux/example/lib/open_multiple_images_page.dart @@ -80,10 +80,9 @@ class MultipleImagesDisplay extends StatelessWidget { children: [ ...files.map( (XFile file) => Flexible( - child: - kIsWeb - ? Image.network(file.path) - : Image.file(File(file.path)), + child: kIsWeb + ? Image.network(file.path) + : Image.file(File(file.path)), ), ), ], diff --git a/packages/file_selector/file_selector_linux/example/pubspec.yaml b/packages/file_selector/file_selector_linux/example/pubspec.yaml index ae1fd0f3234..bf4a8ca7eb4 100644 --- a/packages/file_selector/file_selector_linux/example/pubspec.yaml +++ b/packages/file_selector/file_selector_linux/example/pubspec.yaml @@ -4,8 +4,8 @@ publish_to: 'none' version: 1.0.0+1 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: file_selector_linux: diff --git a/packages/file_selector/file_selector_linux/lib/src/messages.g.dart b/packages/file_selector/file_selector_linux/lib/src/messages.g.dart index 0722bbfac37..552d0cdd023 100644 --- a/packages/file_selector/file_selector_linux/lib/src/messages.g.dart +++ b/packages/file_selector/file_selector_linux/lib/src/messages.g.dart @@ -87,8 +87,8 @@ class PlatformFileChooserOptions { static PlatformFileChooserOptions decode(Object result) { result as List; return PlatformFileChooserOptions( - allowedFileTypes: - (result[0] as List?)?.cast(), + allowedFileTypes: (result[0] as List?) + ?.cast(), currentFolderPath: result[1] as String?, currentName: result[2] as String?, acceptButtonLabel: result[3] as String?, @@ -144,8 +144,9 @@ class FileSelectorApi { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); diff --git a/packages/file_selector/file_selector_linux/pubspec.yaml b/packages/file_selector/file_selector_linux/pubspec.yaml index e5450ed6da9..bd085f3a6a8 100644 --- a/packages/file_selector/file_selector_linux/pubspec.yaml +++ b/packages/file_selector/file_selector_linux/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 0.9.3+2 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" flutter: plugin: diff --git a/packages/file_selector/file_selector_platform_interface/CHANGELOG.md b/packages/file_selector/file_selector_platform_interface/CHANGELOG.md index 8fa2b0d72ff..c47d1cdbdda 100644 --- a/packages/file_selector/file_selector_platform_interface/CHANGELOG.md +++ b/packages/file_selector/file_selector_platform_interface/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. + ## 2.7.0 * Adds `canCreateDirectories` parameter to `FileDialogOptions` to control whether directory creation is enabled during path selection. diff --git a/packages/file_selector/file_selector_platform_interface/lib/src/method_channel/method_channel_file_selector.dart b/packages/file_selector/file_selector_platform_interface/lib/src/method_channel/method_channel_file_selector.dart index d728708f36e..a39a1893388 100644 --- a/packages/file_selector/file_selector_platform_interface/lib/src/method_channel/method_channel_file_selector.dart +++ b/packages/file_selector/file_selector_platform_interface/lib/src/method_channel/method_channel_file_selector.dart @@ -25,10 +25,9 @@ class MethodChannelFileSelector extends FileSelectorPlatform { }) async { final List? path = await _channel .invokeListMethod('openFile', { - 'acceptedTypeGroups': - acceptedTypeGroups - ?.map((XTypeGroup group) => group.toJSON()) - .toList(), + 'acceptedTypeGroups': acceptedTypeGroups + ?.map((XTypeGroup group) => group.toJSON()) + .toList(), 'initialDirectory': initialDirectory, 'confirmButtonText': confirmButtonText, 'multiple': false, @@ -44,10 +43,9 @@ class MethodChannelFileSelector extends FileSelectorPlatform { }) async { final List? pathList = await _channel .invokeListMethod('openFile', { - 'acceptedTypeGroups': - acceptedTypeGroups - ?.map((XTypeGroup group) => group.toJSON()) - .toList(), + 'acceptedTypeGroups': acceptedTypeGroups + ?.map((XTypeGroup group) => group.toJSON()) + .toList(), 'initialDirectory': initialDirectory, 'confirmButtonText': confirmButtonText, 'multiple': true, @@ -63,10 +61,9 @@ class MethodChannelFileSelector extends FileSelectorPlatform { String? confirmButtonText, }) async { return _channel.invokeMethod('getSavePath', { - 'acceptedTypeGroups': - acceptedTypeGroups - ?.map((XTypeGroup group) => group.toJSON()) - .toList(), + 'acceptedTypeGroups': acceptedTypeGroups + ?.map((XTypeGroup group) => group.toJSON()) + .toList(), 'initialDirectory': initialDirectory, 'suggestedName': suggestedName, 'confirmButtonText': confirmButtonText, diff --git a/packages/file_selector/file_selector_platform_interface/lib/src/types/x_type_group.dart b/packages/file_selector/file_selector_platform_interface/lib/src/types/x_type_group.dart index 8b8f5dee238..12761e90504 100644 --- a/packages/file_selector/file_selector_platform_interface/lib/src/types/x_type_group.dart +++ b/packages/file_selector/file_selector_platform_interface/lib/src/types/x_type_group.dart @@ -70,8 +70,7 @@ class XTypeGroup { @Deprecated('Use uniformTypeIdentifiers instead') List? get macUTIs => uniformTypeIdentifiers; - static List? _removeLeadingDots(List? exts) => - exts - ?.map((String ext) => ext.startsWith('.') ? ext.substring(1) : ext) - .toList(); + static List? _removeLeadingDots(List? exts) => exts + ?.map((String ext) => ext.startsWith('.') ? ext.substring(1) : ext) + .toList(); } diff --git a/packages/file_selector/file_selector_platform_interface/pubspec.yaml b/packages/file_selector/file_selector_platform_interface/pubspec.yaml index d68d95826d0..b7ca9094d79 100644 --- a/packages/file_selector/file_selector_platform_interface/pubspec.yaml +++ b/packages/file_selector/file_selector_platform_interface/pubspec.yaml @@ -7,8 +7,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.7.0 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: cross_file: ^0.3.0 diff --git a/packages/file_selector/file_selector_web/CHANGELOG.md b/packages/file_selector/file_selector_web/CHANGELOG.md index 5323271b741..e88f14aef47 100644 --- a/packages/file_selector/file_selector_web/CHANGELOG.md +++ b/packages/file_selector/file_selector_web/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 0.9.4+2 diff --git a/packages/file_selector/file_selector_web/example/integration_test/dom_helper_test.dart b/packages/file_selector/file_selector_web/example/integration_test/dom_helper_test.dart index 18727951ffa..33db0d033ee 100644 --- a/packages/file_selector/file_selector_web/example/integration_test/dom_helper_test.dart +++ b/packages/file_selector/file_selector_web/example/integration_test/dom_helper_test.dart @@ -41,8 +41,8 @@ void main() { setUp(() { domHelper = DomHelper(); - input = - (document.createElement('input') as HTMLInputElement)..type = 'file'; + input = (document.createElement('input') as HTMLInputElement) + ..type = 'file'; }); group('getFiles', () { diff --git a/packages/file_selector/file_selector_web/example/pubspec.yaml b/packages/file_selector/file_selector_web/example/pubspec.yaml index 96fdf0fad6e..5aba7c3be12 100644 --- a/packages/file_selector/file_selector_web/example/pubspec.yaml +++ b/packages/file_selector/file_selector_web/example/pubspec.yaml @@ -2,8 +2,8 @@ name: file_selector_web_integration_tests publish_to: none environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: file_selector_platform_interface: ^2.6.0 diff --git a/packages/file_selector/file_selector_web/lib/src/dom_helper.dart b/packages/file_selector/file_selector_web/lib/src/dom_helper.dart index 0b40c560770..d1070ff4c77 100644 --- a/packages/file_selector/file_selector_web/lib/src/dom_helper.dart +++ b/packages/file_selector/file_selector_web/lib/src/dom_helper.dart @@ -38,11 +38,10 @@ class DomHelper { ); inputElement.onChange.first.then((_) { - final List files = - Iterable.generate( - inputElement.files!.length, - (int i) => inputElement.files!.item(i)!, - ).map(_convertFileToXFile).toList(); + final List files = Iterable.generate( + inputElement.files!.length, + (int i) => inputElement.files!.item(i)!, + ).map(_convertFileToXFile).toList(); inputElement.remove(); completer.complete(files); }); diff --git a/packages/file_selector/file_selector_web/pubspec.yaml b/packages/file_selector/file_selector_web/pubspec.yaml index 52cd67b2c53..1f8f6c3208a 100644 --- a/packages/file_selector/file_selector_web/pubspec.yaml +++ b/packages/file_selector/file_selector_web/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 0.9.4+2 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" flutter: plugin: diff --git a/packages/file_selector/file_selector_windows/CHANGELOG.md b/packages/file_selector/file_selector_windows/CHANGELOG.md index 8eaeeb2292f..3229e765835 100644 --- a/packages/file_selector/file_selector_windows/CHANGELOG.md +++ b/packages/file_selector/file_selector_windows/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 0.9.3+4 diff --git a/packages/file_selector/file_selector_windows/example/lib/get_multiple_directories_page.dart b/packages/file_selector/file_selector_windows/example/lib/get_multiple_directories_page.dart index 8ec229cdb20..be1bdfd40a0 100644 --- a/packages/file_selector/file_selector_windows/example/lib/get_multiple_directories_page.dart +++ b/packages/file_selector/file_selector_windows/example/lib/get_multiple_directories_page.dart @@ -22,8 +22,8 @@ class GetMultipleDirectoriesPage extends StatelessWidget { if (context.mounted) { await showDialog( context: context, - builder: - (BuildContext context) => TextDisplay(directoriesPaths.join('\n')), + builder: (BuildContext context) => + TextDisplay(directoriesPaths.join('\n')), ); } } diff --git a/packages/file_selector/file_selector_windows/example/lib/home_page.dart b/packages/file_selector/file_selector_windows/example/lib/home_page.dart index a4e6f828876..b49884852ba 100644 --- a/packages/file_selector/file_selector_windows/example/lib/home_page.dart +++ b/packages/file_selector/file_selector_windows/example/lib/home_page.dart @@ -54,8 +54,8 @@ class HomePage extends StatelessWidget { ElevatedButton( style: style, child: const Text('Open a get directories dialog'), - onPressed: - () => Navigator.pushNamed(context, '/multi-directories'), + onPressed: () => + Navigator.pushNamed(context, '/multi-directories'), ), ], ), diff --git a/packages/file_selector/file_selector_windows/example/lib/main.dart b/packages/file_selector/file_selector_windows/example/lib/main.dart index f1d207839e6..28a34200274 100644 --- a/packages/file_selector/file_selector_windows/example/lib/main.dart +++ b/packages/file_selector/file_selector_windows/example/lib/main.dart @@ -32,13 +32,13 @@ class MyApp extends StatelessWidget { home: const HomePage(), routes: { '/open/image': (BuildContext context) => const OpenImagePage(), - '/open/images': - (BuildContext context) => const OpenMultipleImagesPage(), + '/open/images': (BuildContext context) => + const OpenMultipleImagesPage(), '/open/text': (BuildContext context) => const OpenTextPage(), '/save/text': (BuildContext context) => SaveTextPage(), '/directory': (BuildContext context) => const GetDirectoryPage(), - '/multi-directories': - (BuildContext context) => const GetMultipleDirectoriesPage(), + '/multi-directories': (BuildContext context) => + const GetMultipleDirectoriesPage(), }, ); } diff --git a/packages/file_selector/file_selector_windows/example/lib/open_multiple_images_page.dart b/packages/file_selector/file_selector_windows/example/lib/open_multiple_images_page.dart index 1b11e49391f..0b9fe352516 100644 --- a/packages/file_selector/file_selector_windows/example/lib/open_multiple_images_page.dart +++ b/packages/file_selector/file_selector_windows/example/lib/open_multiple_images_page.dart @@ -80,10 +80,9 @@ class MultipleImagesDisplay extends StatelessWidget { children: [ ...files.map( (XFile file) => Flexible( - child: - kIsWeb - ? Image.network(file.path) - : Image.file(File(file.path)), + child: kIsWeb + ? Image.network(file.path) + : Image.file(File(file.path)), ), ), ], diff --git a/packages/file_selector/file_selector_windows/example/pubspec.yaml b/packages/file_selector/file_selector_windows/example/pubspec.yaml index 7414ec65fdb..04e934211e9 100644 --- a/packages/file_selector/file_selector_windows/example/pubspec.yaml +++ b/packages/file_selector/file_selector_windows/example/pubspec.yaml @@ -4,8 +4,8 @@ publish_to: 'none' version: 1.0.0 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: file_selector_platform_interface: ^2.6.0 diff --git a/packages/file_selector/file_selector_windows/lib/file_selector_windows.dart b/packages/file_selector/file_selector_windows/lib/file_selector_windows.dart index 4f2ace43976..fe5b7a96362 100644 --- a/packages/file_selector/file_selector_windows/lib/file_selector_windows.dart +++ b/packages/file_selector/file_selector_windows/lib/file_selector_windows.dart @@ -88,10 +88,11 @@ class FileSelectorWindows extends FileSelectorPlatform { return result.paths.isEmpty ? null : FileSaveLocation( - result.paths.first, - activeFilter: - groupIndex == null ? null : acceptedTypeGroups?[groupIndex], - ); + result.paths.first, + activeFilter: groupIndex == null + ? null + : acceptedTypeGroups?[groupIndex], + ); } @override diff --git a/packages/file_selector/file_selector_windows/lib/src/messages.g.dart b/packages/file_selector/file_selector_windows/lib/src/messages.g.dart index e17b8a66411..19b57b6b8a8 100644 --- a/packages/file_selector/file_selector_windows/lib/src/messages.g.dart +++ b/packages/file_selector/file_selector_windows/lib/src/messages.g.dart @@ -151,8 +151,9 @@ class FileSelectorApi { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); diff --git a/packages/file_selector/file_selector_windows/pubspec.yaml b/packages/file_selector/file_selector_windows/pubspec.yaml index d71a5ff09d9..8891c3d1c8a 100644 --- a/packages/file_selector/file_selector_windows/pubspec.yaml +++ b/packages/file_selector/file_selector_windows/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 0.9.3+4 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" flutter: plugin: diff --git a/packages/flutter_lints/CHANGELOG.md b/packages/flutter_lints/CHANGELOG.md index 04c2b8f0a4b..bb25141306c 100644 --- a/packages/flutter_lints/CHANGELOG.md +++ b/packages/flutter_lints/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 6.0.0 diff --git a/packages/flutter_lints/example/pubspec.yaml b/packages/flutter_lints/example/pubspec.yaml index aa21898fdd2..5deb3eb1f88 100644 --- a/packages/flutter_lints/example/pubspec.yaml +++ b/packages/flutter_lints/example/pubspec.yaml @@ -4,7 +4,7 @@ description: A project that showcases how to enable the recommended lints for Fl publish_to: none environment: - sdk: ^3.7.0 + sdk: ^3.8.0 # Add the latest version of `package:flutter_lints` as a dev_dependency. The # lint set provided by this package is activated in the `analysis_options.yaml` diff --git a/packages/flutter_template_images/CHANGELOG.md b/packages/flutter_template_images/CHANGELOG.md index 8f08f288a92..e8a7a0dda0b 100644 --- a/packages/flutter_template_images/CHANGELOG.md +++ b/packages/flutter_template_images/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 5.0.0 diff --git a/packages/flutter_template_images/pubspec.yaml b/packages/flutter_template_images/pubspec.yaml index 3b7a32bde2b..3d4cdaa4e15 100644 --- a/packages/flutter_template_images/pubspec.yaml +++ b/packages/flutter_template_images/pubspec.yaml @@ -5,7 +5,7 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 5.0.0 environment: - sdk: ^3.7.0 + sdk: ^3.8.0 topics: - assets diff --git a/packages/go_router/CHANGELOG.md b/packages/go_router/CHANGELOG.md index 12a6b980934..cd0790837d6 100644 --- a/packages/go_router/CHANGELOG.md +++ b/packages/go_router/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. + ## 17.0.0 - **BREAKING CHANGE** diff --git a/packages/go_router/doc/configuration.md b/packages/go_router/doc/configuration.md index 81be3be03d7..6f56b5959e2 100644 --- a/packages/go_router/doc/configuration.md +++ b/packages/go_router/doc/configuration.md @@ -178,18 +178,16 @@ branches: [ // The screen to display as the root in the first tab of the // bottom navigation bar. path: '/a', - builder: - (BuildContext context, GoRouterState state) => - const RootScreen(label: 'A', detailsPath: '/a/details'), + builder: (BuildContext context, GoRouterState state) => + const RootScreen(label: 'A', detailsPath: '/a/details'), routes: [ // The details screen to display stacked on navigator of the // first tab. This will cover screen A but not the application // shell (bottom navigation bar). GoRoute( path: 'details', - builder: - (BuildContext context, GoRouterState state) => - const DetailsScreen(label: 'A'), + builder: (BuildContext context, GoRouterState state) => + const DetailsScreen(label: 'A'), ), ], ), @@ -207,17 +205,18 @@ which is passed as the last argument to the builder function. Example: ```dart StatefulShellRoute.indexedStack( - builder: ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - // Return the widget that implements the custom shell (in this case - // using a BottomNavigationBar). The StatefulNavigationShell is passed - // to be able access the state of the shell and to navigate to other - // branches in a stateful way. - return ScaffoldWithNavBar(navigationShell: navigationShell); - }, + builder: + ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + // Return the widget that implements the custom shell (in this case + // using a BottomNavigationBar). The StatefulNavigationShell is passed + // to be able access the state of the shell and to navigate to other + // branches in a stateful way. + return ScaffoldWithNavBar(navigationShell: navigationShell); + }, ``` Within the custom shell widget, the StatefulNavigationShell is first and diff --git a/packages/go_router/example/lib/async_redirection.dart b/packages/go_router/example/lib/async_redirection.dart index 6fdc6100323..ddba52ac036 100644 --- a/packages/go_router/example/lib/async_redirection.dart +++ b/packages/go_router/example/lib/async_redirection.dart @@ -39,13 +39,13 @@ class App extends StatelessWidget { routes: [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), ), GoRoute( path: '/login', - builder: - (BuildContext context, GoRouterState state) => const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => + const LoginScreen(), ), ], @@ -89,12 +89,11 @@ class _LoginScreenState extends State @override void initState() { super.initState(); - controller = AnimationController( - vsync: this, - duration: const Duration(seconds: 1), - )..addListener(() { - setState(() {}); - }); + controller = + AnimationController(vsync: this, duration: const Duration(seconds: 1)) + ..addListener(() { + setState(() {}); + }); controller.repeat(); } diff --git a/packages/go_router/example/lib/books/main.dart b/packages/go_router/example/lib/books/main.dart index 2cba6e7bec2..8652f0dbd0e 100644 --- a/packages/go_router/example/lib/books/main.dart +++ b/packages/go_router/example/lib/books/main.dart @@ -40,8 +40,8 @@ class Bookstore extends StatelessWidget { GoRoute(path: '/', redirect: (_, __) => '/books'), GoRoute( path: '/signin', - pageBuilder: - (BuildContext context, GoRouterState state) => FadeTransitionPage( + pageBuilder: (BuildContext context, GoRouterState state) => + FadeTransitionPage( key: state.pageKey, child: SignInScreen( onSignIn: (Credentials credentials) { @@ -55,14 +55,13 @@ class Bookstore extends StatelessWidget { GoRoute(path: '/books', redirect: (_, __) => '/books/popular'), GoRoute( path: '/book/:bookId', - redirect: - (BuildContext context, GoRouterState state) => - '/books/all/${state.pathParameters['bookId']}', + redirect: (BuildContext context, GoRouterState state) => + '/books/all/${state.pathParameters['bookId']}', ), GoRoute( path: '/books/:kind(new|all|popular)', - pageBuilder: - (BuildContext context, GoRouterState state) => FadeTransitionPage( + pageBuilder: (BuildContext context, GoRouterState state) => + FadeTransitionPage( key: _scaffoldKey, child: BookstoreScaffold( selectedTab: ScaffoldTab.books, @@ -84,14 +83,13 @@ class Bookstore extends StatelessWidget { ), GoRoute( path: '/author/:authorId', - redirect: - (BuildContext context, GoRouterState state) => - '/authors/${state.pathParameters['authorId']}', + redirect: (BuildContext context, GoRouterState state) => + '/authors/${state.pathParameters['authorId']}', ), GoRoute( path: '/authors', - pageBuilder: - (BuildContext context, GoRouterState state) => FadeTransitionPage( + pageBuilder: (BuildContext context, GoRouterState state) => + FadeTransitionPage( key: _scaffoldKey, child: const BookstoreScaffold( selectedTab: ScaffoldTab.authors, @@ -113,8 +111,8 @@ class Bookstore extends StatelessWidget { ), GoRoute( path: '/settings', - pageBuilder: - (BuildContext context, GoRouterState state) => FadeTransitionPage( + pageBuilder: (BuildContext context, GoRouterState state) => + FadeTransitionPage( key: _scaffoldKey, child: const BookstoreScaffold( selectedTab: ScaffoldTab.settings, diff --git a/packages/go_router/example/lib/books/src/auth.dart b/packages/go_router/example/lib/books/src/auth.dart index dbe94cee4bb..65a9a470d98 100644 --- a/packages/go_router/example/lib/books/src/auth.dart +++ b/packages/go_router/example/lib/books/src/auth.dart @@ -40,8 +40,7 @@ class BookstoreAuthScope extends InheritedNotifier { }); /// Gets the [BookstoreAuth] above the context. - static BookstoreAuth of(BuildContext context) => - context - .dependOnInheritedWidgetOfExactType()! - .notifier!; + static BookstoreAuth of(BuildContext context) => context + .dependOnInheritedWidgetOfExactType()! + .notifier!; } diff --git a/packages/go_router/example/lib/books/src/data/library.dart b/packages/go_router/example/lib/books/src/data/library.dart index 70f2b5244aa..a211026ff5f 100644 --- a/packages/go_router/example/lib/books/src/data/library.dart +++ b/packages/go_router/example/lib/books/src/data/library.dart @@ -6,32 +6,31 @@ import 'author.dart'; import 'book.dart'; /// Library data mock. -final Library libraryInstance = - Library() - ..addBook( - title: 'Left Hand of Darkness', - authorName: 'Ursula K. Le Guin', - isPopular: true, - isNew: true, - ) - ..addBook( - title: 'Too Like the Lightning', - authorName: 'Ada Palmer', - isPopular: false, - isNew: true, - ) - ..addBook( - title: 'Kindred', - authorName: 'Octavia E. Butler', - isPopular: true, - isNew: false, - ) - ..addBook( - title: 'The Lathe of Heaven', - authorName: 'Ursula K. Le Guin', - isPopular: false, - isNew: false, - ); +final Library libraryInstance = Library() + ..addBook( + title: 'Left Hand of Darkness', + authorName: 'Ursula K. Le Guin', + isPopular: true, + isNew: true, + ) + ..addBook( + title: 'Too Like the Lightning', + authorName: 'Ada Palmer', + isPopular: false, + isNew: true, + ) + ..addBook( + title: 'Kindred', + authorName: 'Octavia E. Butler', + isPopular: true, + isNew: false, + ) + ..addBook( + title: 'The Lathe of Heaven', + authorName: 'Ursula K. Le Guin', + isPopular: false, + isNew: false, + ); /// A library that contains books and authors. class Library { diff --git a/packages/go_router/example/lib/books/src/screens/book_details.dart b/packages/go_router/example/lib/books/src/screens/book_details.dart index 72414d96ad4..83626824f2f 100644 --- a/packages/go_router/example/lib/books/src/screens/book_details.dart +++ b/packages/go_router/example/lib/books/src/screens/book_details.dart @@ -39,9 +39,8 @@ class BookDetailsScreen extends StatelessWidget { onPressed: () { Navigator.of(context).push( MaterialPageRoute( - builder: - (BuildContext context) => - AuthorDetailsScreen(author: book!.author), + builder: (BuildContext context) => + AuthorDetailsScreen(author: book!.author), ), ); }, @@ -49,8 +48,8 @@ class BookDetailsScreen extends StatelessWidget { ), Link( uri: Uri.parse('/author/${book!.author.id}'), - builder: - (BuildContext context, FollowLink? followLink) => TextButton( + builder: (BuildContext context, FollowLink? followLink) => + TextButton( onPressed: followLink, child: const Text('View author (Link)'), ), diff --git a/packages/go_router/example/lib/books/src/screens/settings.dart b/packages/go_router/example/lib/books/src/screens/settings.dart index 2d5dc28ee9e..4b0a386f243 100644 --- a/packages/go_router/example/lib/books/src/screens/settings.dart +++ b/packages/go_router/example/lib/books/src/screens/settings.dart @@ -57,11 +57,10 @@ class SettingsContent extends StatelessWidget { ), Link( uri: Uri.parse('/book/0'), - builder: - (BuildContext context, FollowLink? followLink) => TextButton( - onPressed: followLink, - child: const Text('Go directly to /book/0 (Link)'), - ), + builder: (BuildContext context, FollowLink? followLink) => TextButton( + onPressed: followLink, + child: const Text('Go directly to /book/0 (Link)'), + ), ), TextButton( onPressed: () { @@ -73,25 +72,23 @@ class SettingsContent extends StatelessWidget { (Widget w) => Padding(padding: const EdgeInsets.all(8), child: w), ), TextButton( - onPressed: - () => showDialog( - context: context, - builder: - (BuildContext context) => AlertDialog( - title: const Text('Alert!'), - content: const Text('The alert description goes here.'), - actions: [ - TextButton( - onPressed: () => Navigator.pop(context, 'Cancel'), - child: const Text('Cancel'), - ), - TextButton( - onPressed: () => Navigator.pop(context, 'OK'), - child: const Text('OK'), - ), - ], - ), - ), + onPressed: () => showDialog( + context: context, + builder: (BuildContext context) => AlertDialog( + title: const Text('Alert!'), + content: const Text('The alert description goes here.'), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, 'Cancel'), + child: const Text('Cancel'), + ), + TextButton( + onPressed: () => Navigator.pop(context, 'OK'), + child: const Text('OK'), + ), + ], + ), + ), child: const Text('Show Dialog'), ), ], diff --git a/packages/go_router/example/lib/books/src/widgets/author_list.dart b/packages/go_router/example/lib/books/src/widgets/author_list.dart index 855cd5f1b37..1cfb22014e9 100644 --- a/packages/go_router/example/lib/books/src/widgets/author_list.dart +++ b/packages/go_router/example/lib/books/src/widgets/author_list.dart @@ -20,11 +20,10 @@ class AuthorList extends StatelessWidget { @override Widget build(BuildContext context) => ListView.builder( itemCount: authors.length, - itemBuilder: - (BuildContext context, int index) => ListTile( - title: Text(authors[index].name), - subtitle: Text('${authors[index].books.length} books'), - onTap: onTap != null ? () => onTap!(authors[index]) : null, - ), + itemBuilder: (BuildContext context, int index) => ListTile( + title: Text(authors[index].name), + subtitle: Text('${authors[index].books.length} books'), + onTap: onTap != null ? () => onTap!(authors[index]) : null, + ), ); } diff --git a/packages/go_router/example/lib/books/src/widgets/book_list.dart b/packages/go_router/example/lib/books/src/widgets/book_list.dart index 330e4b2e983..3c78b665591 100644 --- a/packages/go_router/example/lib/books/src/widgets/book_list.dart +++ b/packages/go_router/example/lib/books/src/widgets/book_list.dart @@ -20,11 +20,10 @@ class BookList extends StatelessWidget { @override Widget build(BuildContext context) => ListView.builder( itemCount: books.length, - itemBuilder: - (BuildContext context, int index) => ListTile( - title: Text(books[index].title), - subtitle: Text(books[index].author.name), - onTap: onTap != null ? () => onTap!(books[index]) : null, - ), + itemBuilder: (BuildContext context, int index) => ListTile( + title: Text(books[index].title), + subtitle: Text(books[index].author.name), + onTap: onTap != null ? () => onTap!(books[index]) : null, + ), ); } diff --git a/packages/go_router/example/lib/extra_codec.dart b/packages/go_router/example/lib/extra_codec.dart index 5684b83f135..5667986dd01 100644 --- a/packages/go_router/example/lib/extra_codec.dart +++ b/packages/go_router/example/lib/extra_codec.dart @@ -15,8 +15,8 @@ final GoRouter _router = GoRouter( routes: [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), ), ], extraCodec: const MyExtraCodec(), diff --git a/packages/go_router/example/lib/named_routes.dart b/packages/go_router/example/lib/named_routes.dart index 41d461b47a0..4223486f019 100644 --- a/packages/go_router/example/lib/named_routes.dart +++ b/packages/go_router/example/lib/named_routes.dart @@ -77,15 +77,14 @@ class App extends StatelessWidget { GoRoute( name: 'home', path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), routes: [ GoRoute( name: 'family', path: 'family/:fid', - builder: - (BuildContext context, GoRouterState state) => - FamilyScreen(fid: state.pathParameters['fid']!), + builder: (BuildContext context, GoRouterState state) => + FamilyScreen(fid: state.pathParameters['fid']!), routes: [ GoRoute( name: 'person', @@ -119,13 +118,12 @@ class HomeScreen extends StatelessWidget { for (final MapEntry entry in _families.entries) ListTile( title: Text(entry.value.name), - onTap: - () => context.go( - context.namedLocation( - 'family', - pathParameters: {'fid': entry.key}, - ), - ), + onTap: () => context.go( + context.namedLocation( + 'family', + pathParameters: {'fid': entry.key}, + ), + ), ), ], ), @@ -151,17 +149,16 @@ class FamilyScreen extends StatelessWidget { for (final MapEntry entry in people.entries) ListTile( title: Text(entry.value.name), - onTap: - () => context.go( - context.namedLocation( - 'person', - pathParameters: { - 'fid': fid, - 'pid': entry.key, - }, - queryParameters: {'qid': 'quid'}, - ), - ), + onTap: () => context.go( + context.namedLocation( + 'person', + pathParameters: { + 'fid': fid, + 'pid': entry.key, + }, + queryParameters: {'qid': 'quid'}, + ), + ), ), ], ), diff --git a/packages/go_router/example/lib/others/custom_stateful_shell_route.dart b/packages/go_router/example/lib/others/custom_stateful_shell_route.dart index 78a84868b9d..0755d2bf330 100644 --- a/packages/go_router/example/lib/others/custom_stateful_shell_route.dart +++ b/packages/go_router/example/lib/others/custom_stateful_shell_route.dart @@ -50,36 +50,38 @@ class NestedTabNavigationExampleApp extends StatelessWidget { initialLocation: '/a', routes: [ StatefulShellRoute( - builder: ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - // This nested StatefulShellRoute demonstrates the use of a - // custom container for the branch Navigators. In this implementation, - // no customization is done in the builder function (navigationShell - // itself is simply used as the Widget for the route). Instead, the - // navigatorContainerBuilder function below is provided to - // customize the container for the branch Navigators. - return navigationShell; - }, - navigatorContainerBuilder: ( - BuildContext context, - StatefulNavigationShell navigationShell, - List children, - ) { - // Returning a customized container for the branch - // Navigators (i.e. the `List children` argument). - // - // See ScaffoldWithNavBar for more details on how the children - // are managed (using AnimatedBranchContainer). - return ScaffoldWithNavBar( - navigationShell: navigationShell, - children: children, - ); - // NOTE: To use a Cupertino version of ScaffoldWithNavBar, replace - // ScaffoldWithNavBar above with CupertinoScaffoldWithNavBar. - }, + builder: + ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + // This nested StatefulShellRoute demonstrates the use of a + // custom container for the branch Navigators. In this implementation, + // no customization is done in the builder function (navigationShell + // itself is simply used as the Widget for the route). Instead, the + // navigatorContainerBuilder function below is provided to + // customize the container for the branch Navigators. + return navigationShell; + }, + navigatorContainerBuilder: + ( + BuildContext context, + StatefulNavigationShell navigationShell, + List children, + ) { + // Returning a customized container for the branch + // Navigators (i.e. the `List children` argument). + // + // See ScaffoldWithNavBar for more details on how the children + // are managed (using AnimatedBranchContainer). + return ScaffoldWithNavBar( + navigationShell: navigationShell, + children: children, + ); + // NOTE: To use a Cupertino version of ScaffoldWithNavBar, replace + // ScaffoldWithNavBar above with CupertinoScaffoldWithNavBar. + }, branches: [ // The route branch for the first tab of the bottom navigation bar. StatefulShellBranch( @@ -89,18 +91,16 @@ class NestedTabNavigationExampleApp extends StatelessWidget { // The screen to display as the root in the first tab of the // bottom navigation bar. path: '/a', - builder: - (BuildContext context, GoRouterState state) => - const RootScreenA(), + builder: (BuildContext context, GoRouterState state) => + const RootScreenA(), routes: [ // The details screen to display stacked on navigator of the // first tab. This will cover screen A but not the application // shell (bottom navigation bar). GoRoute( path: 'details', - builder: - (BuildContext context, GoRouterState state) => - const DetailsScreen(label: 'A'), + builder: (BuildContext context, GoRouterState state) => + const DetailsScreen(label: 'A'), ), ], ), @@ -120,33 +120,35 @@ class NestedTabNavigationExampleApp extends StatelessWidget { // defaultLocation: '/b1', routes: [ StatefulShellRoute( - builder: ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - // Just like with the top level StatefulShellRoute, no - // customization is done in the builder function. - return navigationShell; - }, - navigatorContainerBuilder: ( - BuildContext context, - StatefulNavigationShell navigationShell, - List children, - ) { - // Returning a customized container for the branch - // Navigators (i.e. the `List children` argument). - // - // See TabbedRootScreen for more details on how the children - // are managed (in a TabBarView). - return TabbedRootScreen( - navigationShell: navigationShell, - key: tabbedRootScreenKey, - children: children, - ); - // NOTE: To use a PageView version of TabbedRootScreen, - // replace TabbedRootScreen above with PagedRootScreen. - }, + builder: + ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + // Just like with the top level StatefulShellRoute, no + // customization is done in the builder function. + return navigationShell; + }, + navigatorContainerBuilder: + ( + BuildContext context, + StatefulNavigationShell navigationShell, + List children, + ) { + // Returning a customized container for the branch + // Navigators (i.e. the `List children` argument). + // + // See TabbedRootScreen for more details on how the children + // are managed (in a TabBarView). + return TabbedRootScreen( + navigationShell: navigationShell, + key: tabbedRootScreenKey, + children: children, + ); + // NOTE: To use a PageView version of TabbedRootScreen, + // replace TabbedRootScreen above with PagedRootScreen. + }, // This bottom tab uses a nested shell, wrapping sub routes in a // top TabBar. branches: [ @@ -155,12 +157,11 @@ class NestedTabNavigationExampleApp extends StatelessWidget { routes: [ GoRoute( path: '/b1', - builder: - (BuildContext context, GoRouterState state) => - const TabScreen( - label: 'B1', - detailsPath: '/b1/details', - ), + builder: (BuildContext context, GoRouterState state) => + const TabScreen( + label: 'B1', + detailsPath: '/b1/details', + ), routes: [ GoRoute( path: 'details', @@ -183,12 +184,11 @@ class NestedTabNavigationExampleApp extends StatelessWidget { routes: [ GoRoute( path: '/b2', - builder: - (BuildContext context, GoRouterState state) => - const TabScreen( - label: 'B2', - detailsPath: '/b2/details', - ), + builder: (BuildContext context, GoRouterState state) => + const TabScreen( + label: 'B2', + detailsPath: '/b2/details', + ), routes: [ GoRoute( path: 'details', @@ -362,18 +362,17 @@ class AnimatedBranchContainer extends StatelessWidget { @override Widget build(BuildContext context) { return Stack( - children: - children.mapIndexed((int index, Widget navigator) { - return AnimatedScale( - scale: index == currentIndex ? 1 : 1.5, - duration: const Duration(milliseconds: 400), - child: AnimatedOpacity( - opacity: index == currentIndex ? 1 : 0, - duration: const Duration(milliseconds: 400), - child: _branchNavigatorWrapper(index, navigator), - ), - ); - }).toList(), + children: children.mapIndexed((int index, Widget navigator) { + return AnimatedScale( + scale: index == currentIndex ? 1 : 1.5, + duration: const Duration(milliseconds: 400), + child: AnimatedOpacity( + opacity: index == currentIndex ? 1 : 0, + duration: const Duration(milliseconds: 400), + child: _branchNavigatorWrapper(index, navigator), + ), + ); + }).toList(), ); } @@ -554,10 +553,9 @@ class TabbedRootScreenState extends State @override Widget build(BuildContext context) { - final List tabs = - widget.children - .mapIndexed((int i, _) => Tab(text: 'Tab ${i + 1}')) - .toList(); + final List tabs = widget.children + .mapIndexed((int i, _) => Tab(text: 'Tab ${i + 1}')) + .toList(); return Scaffold( appBar: AppBar( diff --git a/packages/go_router/example/lib/others/error_screen.dart b/packages/go_router/example/lib/others/error_screen.dart index 885ada3afe0..27b30a956f0 100644 --- a/packages/go_router/example/lib/others/error_screen.dart +++ b/packages/go_router/example/lib/others/error_screen.dart @@ -23,18 +23,17 @@ class App extends StatelessWidget { routes: [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const Page1Screen(), + builder: (BuildContext context, GoRouterState state) => + const Page1Screen(), ), GoRoute( path: '/page2', - builder: - (BuildContext context, GoRouterState state) => const Page2Screen(), + builder: (BuildContext context, GoRouterState state) => + const Page2Screen(), ), ], - errorBuilder: - (BuildContext context, GoRouterState state) => - ErrorScreen(state.error!), + errorBuilder: (BuildContext context, GoRouterState state) => + ErrorScreen(state.error!), ); } diff --git a/packages/go_router/example/lib/others/extra_param.dart b/packages/go_router/example/lib/others/extra_param.dart index e0b9495b39b..9644aab6708 100644 --- a/packages/go_router/example/lib/others/extra_param.dart +++ b/packages/go_router/example/lib/others/extra_param.dart @@ -62,8 +62,8 @@ class App extends StatelessWidget { GoRoute( name: 'home', path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), routes: [ GoRoute( name: 'family', @@ -94,11 +94,10 @@ class HomeScreen extends StatelessWidget { for (final MapEntry entry in _families.entries) ListTile( title: Text(entry.value.name), - onTap: - () => context.goNamed( - 'family', - extra: {'fid': entry.key}, - ), + onTap: () => context.goNamed( + 'family', + extra: {'fid': entry.key}, + ), ), ], ), diff --git a/packages/go_router/example/lib/others/init_loc.dart b/packages/go_router/example/lib/others/init_loc.dart index 6ba03a259f3..a980b8df619 100644 --- a/packages/go_router/example/lib/others/init_loc.dart +++ b/packages/go_router/example/lib/others/init_loc.dart @@ -24,18 +24,18 @@ class App extends StatelessWidget { routes: [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const Page1Screen(), + builder: (BuildContext context, GoRouterState state) => + const Page1Screen(), ), GoRoute( path: '/page2', - builder: - (BuildContext context, GoRouterState state) => const Page2Screen(), + builder: (BuildContext context, GoRouterState state) => + const Page2Screen(), ), GoRoute( path: '/page3', - builder: - (BuildContext context, GoRouterState state) => const Page3Screen(), + builder: (BuildContext context, GoRouterState state) => + const Page3Screen(), ), ], ); diff --git a/packages/go_router/example/lib/others/nav_observer.dart b/packages/go_router/example/lib/others/nav_observer.dart index 4fd74c0549f..fea069fa3c2 100644 --- a/packages/go_router/example/lib/others/nav_observer.dart +++ b/packages/go_router/example/lib/others/nav_observer.dart @@ -26,22 +26,20 @@ class App extends StatelessWidget { GoRoute( // if there's no name, path will be used as name for observers path: '/', - builder: - (BuildContext context, GoRouterState state) => const Page1Screen(), + builder: (BuildContext context, GoRouterState state) => + const Page1Screen(), routes: [ GoRoute( name: 'page2', path: 'page2/:p1', - builder: - (BuildContext context, GoRouterState state) => - const Page2Screen(), + builder: (BuildContext context, GoRouterState state) => + const Page2Screen(), routes: [ GoRoute( name: 'page3', path: 'page3', - builder: - (BuildContext context, GoRouterState state) => - const Page3Screen(), + builder: (BuildContext context, GoRouterState state) => + const Page3Screen(), ), ], ), @@ -107,12 +105,11 @@ class Page1Screen extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.center, children: [ ElevatedButton( - onPressed: - () => context.goNamed( - 'page2', - pathParameters: {'p1': 'pv1'}, - queryParameters: {'q1': 'qv1'}, - ), + onPressed: () => context.goNamed( + 'page2', + pathParameters: {'p1': 'pv1'}, + queryParameters: {'q1': 'qv1'}, + ), child: const Text('Go to page 2'), ), ], @@ -134,11 +131,10 @@ class Page2Screen extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.center, children: [ ElevatedButton( - onPressed: - () => context.goNamed( - 'page3', - pathParameters: {'p1': 'pv2'}, - ), + onPressed: () => context.goNamed( + 'page3', + pathParameters: {'p1': 'pv2'}, + ), child: const Text('Go to page 3'), ), ], diff --git a/packages/go_router/example/lib/others/push.dart b/packages/go_router/example/lib/others/push.dart index 25ae99822e2..f915bae847f 100644 --- a/packages/go_router/example/lib/others/push.dart +++ b/packages/go_router/example/lib/others/push.dart @@ -23,14 +23,13 @@ class App extends StatelessWidget { routes: [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => - const Page1ScreenWithPush(), + builder: (BuildContext context, GoRouterState state) => + const Page1ScreenWithPush(), ), GoRoute( path: '/page2', - builder: - (BuildContext context, GoRouterState state) => Page2ScreenWithPush( + builder: (BuildContext context, GoRouterState state) => + Page2ScreenWithPush( int.parse(state.uri.queryParameters['push-count']!), ), ), @@ -87,8 +86,8 @@ class Page2ScreenWithPush extends StatelessWidget { Padding( padding: const EdgeInsets.all(8), child: ElevatedButton( - onPressed: - () => context.push('/page2?push-count=${pushCount + 1}'), + onPressed: () => + context.push('/page2?push-count=${pushCount + 1}'), child: const Text('Push page 2 (again)'), ), ), diff --git a/packages/go_router/example/lib/others/router_neglect.dart b/packages/go_router/example/lib/others/router_neglect.dart index d529d756c45..3c1e4bcc768 100644 --- a/packages/go_router/example/lib/others/router_neglect.dart +++ b/packages/go_router/example/lib/others/router_neglect.dart @@ -26,13 +26,13 @@ class App extends StatelessWidget { routes: [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const Page1Screen(), + builder: (BuildContext context, GoRouterState state) => + const Page1Screen(), ), GoRoute( path: '/page2', - builder: - (BuildContext context, GoRouterState state) => const Page2Screen(), + builder: (BuildContext context, GoRouterState state) => + const Page2Screen(), ), ], ); @@ -59,8 +59,8 @@ class Page1Screen extends StatelessWidget { // turn off history tracking in the browser for this navigation; // note that this isn't necessary when you've set routerNeglect // but it does illustrate the technique - onPressed: - () => Router.neglect(context, () => context.push('/page2')), + onPressed: () => + Router.neglect(context, () => context.push('/page2')), child: const Text('Push page 2'), ), ], diff --git a/packages/go_router/example/lib/others/transitions.dart b/packages/go_router/example/lib/others/transitions.dart index 02ab8fa899c..d95862b1962 100644 --- a/packages/go_router/example/lib/others/transitions.dart +++ b/packages/go_router/example/lib/others/transitions.dart @@ -24,99 +24,94 @@ class App extends StatelessWidget { GoRoute(path: '/', redirect: (_, __) => '/none'), GoRoute( path: '/fade', - pageBuilder: - (BuildContext context, GoRouterState state) => - CustomTransitionPage( - key: state.pageKey, - child: const ExampleTransitionsScreen( - kind: 'fade', - color: Colors.red, - ), - transitionsBuilder: - ( - BuildContext context, - Animation animation, - Animation secondaryAnimation, - Widget child, - ) => FadeTransition(opacity: animation, child: child), - ), + pageBuilder: (BuildContext context, GoRouterState state) => + CustomTransitionPage( + key: state.pageKey, + child: const ExampleTransitionsScreen( + kind: 'fade', + color: Colors.red, + ), + transitionsBuilder: + ( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + Widget child, + ) => FadeTransition(opacity: animation, child: child), + ), ), GoRoute( path: '/scale', - pageBuilder: - (BuildContext context, GoRouterState state) => - CustomTransitionPage( - key: state.pageKey, - child: const ExampleTransitionsScreen( - kind: 'scale', - color: Colors.green, - ), - transitionsBuilder: - ( - BuildContext context, - Animation animation, - Animation secondaryAnimation, - Widget child, - ) => ScaleTransition(scale: animation, child: child), - ), + pageBuilder: (BuildContext context, GoRouterState state) => + CustomTransitionPage( + key: state.pageKey, + child: const ExampleTransitionsScreen( + kind: 'scale', + color: Colors.green, + ), + transitionsBuilder: + ( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + Widget child, + ) => ScaleTransition(scale: animation, child: child), + ), ), GoRoute( path: '/slide', - pageBuilder: - (BuildContext context, GoRouterState state) => - CustomTransitionPage( - key: state.pageKey, - child: const ExampleTransitionsScreen( - kind: 'slide', - color: Colors.yellow, + pageBuilder: (BuildContext context, GoRouterState state) => + CustomTransitionPage( + key: state.pageKey, + child: const ExampleTransitionsScreen( + kind: 'slide', + color: Colors.yellow, + ), + transitionsBuilder: + ( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + Widget child, + ) => SlideTransition( + position: animation.drive( + Tween( + begin: const Offset(0.25, 0.25), + end: Offset.zero, + ).chain(CurveTween(curve: Curves.easeIn)), + ), + child: child, ), - transitionsBuilder: - ( - BuildContext context, - Animation animation, - Animation secondaryAnimation, - Widget child, - ) => SlideTransition( - position: animation.drive( - Tween( - begin: const Offset(0.25, 0.25), - end: Offset.zero, - ).chain(CurveTween(curve: Curves.easeIn)), - ), - child: child, - ), - ), + ), ), GoRoute( path: '/rotation', - pageBuilder: - (BuildContext context, GoRouterState state) => - CustomTransitionPage( - key: state.pageKey, - child: const ExampleTransitionsScreen( - kind: 'rotation', - color: Colors.purple, - ), - transitionsBuilder: - ( - BuildContext context, - Animation animation, - Animation secondaryAnimation, - Widget child, - ) => RotationTransition(turns: animation, child: child), - ), + pageBuilder: (BuildContext context, GoRouterState state) => + CustomTransitionPage( + key: state.pageKey, + child: const ExampleTransitionsScreen( + kind: 'rotation', + color: Colors.purple, + ), + transitionsBuilder: + ( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + Widget child, + ) => RotationTransition(turns: animation, child: child), + ), ), GoRoute( path: '/none', - pageBuilder: - (BuildContext context, GoRouterState state) => - NoTransitionPage( - key: state.pageKey, - child: const ExampleTransitionsScreen( - kind: 'none', - color: Colors.white, - ), - ), + pageBuilder: (BuildContext context, GoRouterState state) => + NoTransitionPage( + key: state.pageKey, + child: const ExampleTransitionsScreen( + kind: 'none', + color: Colors.white, + ), + ), ), ], ); diff --git a/packages/go_router/example/lib/path_and_query_parameters.dart b/packages/go_router/example/lib/path_and_query_parameters.dart index d444b99e021..6cd8a4b77d3 100755 --- a/packages/go_router/example/lib/path_and_query_parameters.dart +++ b/packages/go_router/example/lib/path_and_query_parameters.dart @@ -73,8 +73,8 @@ class App extends StatelessWidget { routes: [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), routes: [ GoRoute( name: 'family', @@ -128,10 +128,9 @@ class FamilyScreen extends StatelessWidget { @override Widget build(BuildContext context) { final Map newQueries; - final List names = - _families[fid]!.people.values - .map((Person p) => p.name) - .toList(); + final List names = _families[fid]!.people.values + .map((Person p) => p.name) + .toList(); names.sort(); if (asc) { newQueries = const {'sort': 'desc'}; @@ -143,12 +142,11 @@ class FamilyScreen extends StatelessWidget { title: Text(_families[fid]!.name), actions: [ IconButton( - onPressed: - () => context.goNamed( - 'family', - pathParameters: {'fid': fid}, - queryParameters: newQueries, - ), + onPressed: () => context.goNamed( + 'family', + pathParameters: {'fid': fid}, + queryParameters: newQueries, + ), tooltip: 'sort ascending or descending', icon: const Icon(Icons.sort), ), diff --git a/packages/go_router/example/lib/push_with_shell_route.dart b/packages/go_router/example/lib/push_with_shell_route.dart index e51f02deb68..95d04c5be0e 100644 --- a/packages/go_router/example/lib/push_with_shell_route.dart +++ b/packages/go_router/example/lib/push_with_shell_route.dart @@ -38,10 +38,9 @@ class PushWithShellRouteExampleApp extends StatelessWidget { ), GoRoute( path: '/shell1', - pageBuilder: - (_, __) => const NoTransitionPage( - child: Center(child: Text('shell1 body')), - ), + pageBuilder: (_, __) => const NoTransitionPage( + child: Center(child: Text('shell1 body')), + ), ), ], ), @@ -88,7 +87,10 @@ class ScaffoldForShell1 extends StatelessWidget { @override Widget build(BuildContext context) { - return Scaffold(appBar: AppBar(title: const Text('shell1')), body: child); + return Scaffold( + appBar: AppBar(title: const Text('shell1')), + body: child, + ); } } @@ -103,7 +105,10 @@ class ScaffoldForShell2 extends StatelessWidget { @override Widget build(BuildContext context) { - return Scaffold(appBar: AppBar(title: const Text('shell2')), body: child); + return Scaffold( + appBar: AppBar(title: const Text('shell2')), + body: child, + ); } } diff --git a/packages/go_router/example/lib/redirection.dart b/packages/go_router/example/lib/redirection.dart index b95ecb5d15d..449324b93c3 100644 --- a/packages/go_router/example/lib/redirection.dart +++ b/packages/go_router/example/lib/redirection.dart @@ -61,13 +61,13 @@ class App extends StatelessWidget { routes: [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), ), GoRoute( path: '/login', - builder: - (BuildContext context, GoRouterState state) => const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => + const LoginScreen(), ), ], diff --git a/packages/go_router/example/lib/routing_config.dart b/packages/go_router/example/lib/routing_config.dart index 5a47615ab11..209e1176c34 100644 --- a/packages/go_router/example/lib/routing_config.dart +++ b/packages/go_router/example/lib/routing_config.dart @@ -25,22 +25,21 @@ class _MyAppState extends State { late final GoRouter router = GoRouter.routingConfig( routingConfig: myConfig, - errorBuilder: - (_, GoRouterState state) => Scaffold( - appBar: AppBar(title: const Text('Page not found')), - body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Text('${state.uri} does not exist'), - ElevatedButton( - onPressed: () => router.go('/'), - child: const Text('Go to home'), - ), - ], + errorBuilder: (_, GoRouterState state) => Scaffold( + appBar: AppBar(title: const Text('Page not found')), + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text('${state.uri} does not exist'), + ElevatedButton( + onPressed: () => router.go('/'), + child: const Text('Go to home'), ), - ), + ], ), + ), + ), ); RoutingConfig _generateRoutingConfig() { @@ -56,20 +55,18 @@ class _MyAppState extends State { mainAxisAlignment: MainAxisAlignment.center, children: [ ElevatedButton( - onPressed: - isNewRouteAdded - ? null - : () { - setState(() { - isNewRouteAdded = true; - // Modify the routing config. - myConfig.value = _generateRoutingConfig(); - }); - }, - child: - isNewRouteAdded - ? const Text('A route has been added') - : const Text('Add a new route'), + onPressed: isNewRouteAdded + ? null + : () { + setState(() { + isNewRouteAdded = true; + // Modify the routing config. + myConfig.value = _generateRoutingConfig(); + }); + }, + child: isNewRouteAdded + ? const Text('A route has been added') + : const Text('Add a new route'), ), ElevatedButton( onPressed: () { diff --git a/packages/go_router/example/lib/shell_route_top_route.dart b/packages/go_router/example/lib/shell_route_top_route.dart index a4652edc630..9fa2df1e9ee 100644 --- a/packages/go_router/example/lib/shell_route_top_route.dart +++ b/packages/go_router/example/lib/shell_route_top_route.dart @@ -178,13 +178,13 @@ class ScaffoldWithNavBar extends StatelessWidget { /// The [Scaffold]'s default back button cannot be used because it doesn't /// have the context of the current child. Widget? _buildLeadingButton(BuildContext context) { - final RouteMatchList currentConfiguration = - GoRouter.of(context).routerDelegate.currentConfiguration; + final RouteMatchList currentConfiguration = GoRouter.of( + context, + ).routerDelegate.currentConfiguration; final RouteMatch lastMatch = currentConfiguration.last; - final Uri location = - lastMatch is ImperativeRouteMatch - ? lastMatch.matches.uri - : currentConfiguration.uri; + final Uri location = lastMatch is ImperativeRouteMatch + ? lastMatch.matches.uri + : currentConfiguration.uri; final bool canPop = location.pathSegments.length > 1; return canPop ? BackButton(onPressed: GoRouter.of(context).pop) : null; } diff --git a/packages/go_router/example/lib/state_restoration/shell_route_state_restoration.dart b/packages/go_router/example/lib/state_restoration/shell_route_state_restoration.dart index 5d6b60667ba..e3ee30b9fc2 100644 --- a/packages/go_router/example/lib/state_restoration/shell_route_state_restoration.dart +++ b/packages/go_router/example/lib/state_restoration/shell_route_state_restoration.dart @@ -29,16 +29,13 @@ class _AppState extends State { routes: [ ShellRoute( restorationScopeId: 'onboardingShell', - pageBuilder: ( - BuildContext context, - GoRouterState state, - Widget child, - ) { - return MaterialPage( - restorationId: 'onboardingPage', - child: OnboardingScaffold(child: child), - ); - }, + pageBuilder: + (BuildContext context, GoRouterState state, Widget child) { + return MaterialPage( + restorationId: 'onboardingPage', + child: OnboardingScaffold(child: child), + ); + }, routes: [ GoRoute( path: 'welcome', diff --git a/packages/go_router/example/lib/state_restoration/stateful_shell_route_state_restoration.dart b/packages/go_router/example/lib/state_restoration/stateful_shell_route_state_restoration.dart index 962c60cae86..a81a1031b7c 100644 --- a/packages/go_router/example/lib/state_restoration/stateful_shell_route_state_restoration.dart +++ b/packages/go_router/example/lib/state_restoration/stateful_shell_route_state_restoration.dart @@ -23,16 +23,17 @@ class _AppState extends State { routes: [ StatefulShellRoute.indexedStack( restorationScopeId: 'appShell', - pageBuilder: ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - return MaterialPage( - restorationId: 'appShellPage', - child: AppShell(navigationShell: navigationShell), - ); - }, + pageBuilder: + ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + return MaterialPage( + restorationId: 'appShellPage', + child: AppShell(navigationShell: navigationShell), + ); + }, branches: [ StatefulShellBranch( restorationScopeId: 'homeBranch', diff --git a/packages/go_router/example/lib/stateful_shell_route.dart b/packages/go_router/example/lib/stateful_shell_route.dart index 159f50184a1..39e14ad53c3 100644 --- a/packages/go_router/example/lib/stateful_shell_route.dart +++ b/packages/go_router/example/lib/stateful_shell_route.dart @@ -31,17 +31,18 @@ class NestedTabNavigationExampleApp extends StatelessWidget { routes: [ // #docregion configuration-builder StatefulShellRoute.indexedStack( - builder: ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - // Return the widget that implements the custom shell (in this case - // using a BottomNavigationBar). The StatefulNavigationShell is passed - // to be able access the state of the shell and to navigate to other - // branches in a stateful way. - return ScaffoldWithNavBar(navigationShell: navigationShell); - }, + builder: + ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + // Return the widget that implements the custom shell (in this case + // using a BottomNavigationBar). The StatefulNavigationShell is passed + // to be able access the state of the shell and to navigate to other + // branches in a stateful way. + return ScaffoldWithNavBar(navigationShell: navigationShell); + }, // #enddocregion configuration-builder // #docregion configuration-branches branches: [ @@ -53,18 +54,16 @@ class NestedTabNavigationExampleApp extends StatelessWidget { // The screen to display as the root in the first tab of the // bottom navigation bar. path: '/a', - builder: - (BuildContext context, GoRouterState state) => - const RootScreen(label: 'A', detailsPath: '/a/details'), + builder: (BuildContext context, GoRouterState state) => + const RootScreen(label: 'A', detailsPath: '/a/details'), routes: [ // The details screen to display stacked on navigator of the // first tab. This will cover screen A but not the application // shell (bottom navigation bar). GoRoute( path: 'details', - builder: - (BuildContext context, GoRouterState state) => - const DetailsScreen(label: 'A'), + builder: (BuildContext context, GoRouterState state) => + const DetailsScreen(label: 'A'), ), ], ), @@ -83,22 +82,20 @@ class NestedTabNavigationExampleApp extends StatelessWidget { // The screen to display as the root in the second tab of the // bottom navigation bar. path: '/b', - builder: - (BuildContext context, GoRouterState state) => - const RootScreen( - label: 'B', - detailsPath: '/b/details/1', - secondDetailsPath: '/b/details/2', - ), + builder: (BuildContext context, GoRouterState state) => + const RootScreen( + label: 'B', + detailsPath: '/b/details/1', + secondDetailsPath: '/b/details/2', + ), routes: [ GoRoute( path: 'details/:param', - builder: - (BuildContext context, GoRouterState state) => - DetailsScreen( - label: 'B', - param: state.pathParameters['param'], - ), + builder: (BuildContext context, GoRouterState state) => + DetailsScreen( + label: 'B', + param: state.pathParameters['param'], + ), ), ], ), @@ -112,15 +109,13 @@ class NestedTabNavigationExampleApp extends StatelessWidget { // The screen to display as the root in the third tab of the // bottom navigation bar. path: '/c', - builder: - (BuildContext context, GoRouterState state) => - const RootScreen(label: 'C', detailsPath: '/c/details'), + builder: (BuildContext context, GoRouterState state) => + const RootScreen(label: 'C', detailsPath: '/c/details'), routes: [ GoRoute( path: 'details', - builder: - (BuildContext context, GoRouterState state) => - DetailsScreen(label: 'C', extra: state.extra), + builder: (BuildContext context, GoRouterState state) => + DetailsScreen(label: 'C', extra: state.extra), ), ], ), diff --git a/packages/go_router/example/lib/top_level_on_enter.dart b/packages/go_router/example/lib/top_level_on_enter.dart index fc0fa1e5871..30cd06a83cc 100644 --- a/packages/go_router/example/lib/top_level_on_enter.dart +++ b/packages/go_router/example/lib/top_level_on_enter.dart @@ -50,105 +50,105 @@ class App extends StatelessWidget { // If anything goes sideways during parsing/guards/redirects, // surface a friendly message and offer a one-tap “Go Home”. - onException: ( - BuildContext context, - GoRouterState state, - GoRouter router, - ) { - // Show a user-friendly error message - if (context.mounted) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text('Navigation error: ${state.error}'), - backgroundColor: Colors.red, - duration: const Duration(seconds: 5), - action: SnackBarAction( - label: 'Go Home', - onPressed: () => router.go('/home'), - ), - ), - ); - } - // Log the error for debugging - debugPrint('Router exception: ${state.error}'); - - // Navigate to error screen if needed - if (state.uri.path == '/crash-test') { - router.go('/error'); - } - }, + onException: + (BuildContext context, GoRouterState state, GoRouter router) { + // Show a user-friendly error message + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Navigation error: ${state.error}'), + backgroundColor: Colors.red, + duration: const Duration(seconds: 5), + action: SnackBarAction( + label: 'Go Home', + onPressed: () => router.go('/home'), + ), + ), + ); + } + // Log the error for debugging + debugPrint('Router exception: ${state.error}'); + + // Navigate to error screen if needed + if (state.uri.path == '/crash-test') { + router.go('/error'); + } + }, /// Top-level guard runs BEFORE legacy top-level redirects and route-level redirects. /// Return: /// - `Allow()` to proceed (optionally with `then:` side-effects) /// - `Block.stop()` to cancel navigation immediately /// - `Block.then(() => ...)` to cancel navigation and run follow-up work - onEnter: ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter router, - ) async { - // Example: fire-and-forget analytics for deep links; never block the nav - if (next.uri.hasQuery || next.uri.hasFragment) { - // Don't await: keep the guard non-blocking for best UX. - unawaited(ReferralService.trackDeepLink(next.uri)); - } - - switch (next.uri.path) { - // Block deep-link routes that should never render a page - // (we stay on the current page and show a lightweight UI instead). - case '/referral': - { - final String? code = next.uri.queryParameters['code']; - if (code != null) { - if (context.mounted) { - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar( - content: Text('Processing referral code...'), - duration: Duration(seconds: 2), - ), - ); - } - // Do the real work in the background; don’t keep the user waiting. - await _processReferralCodeInBackground(context, code); - } - return const Block.stop(); // keep user where they are + onEnter: + ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter router, + ) async { + // Example: fire-and-forget analytics for deep links; never block the nav + if (next.uri.hasQuery || next.uri.hasFragment) { + // Don't await: keep the guard non-blocking for best UX. + unawaited(ReferralService.trackDeepLink(next.uri)); } - // Simulate an OAuth callback: do background work + toast; never show a page at /auth - case '/auth': - { - final String? token = next.uri.queryParameters['token']; - if (token != null) { - _handleAuthToken(context, token); - return const Block.stop(); // cancel showing any /auth page - } - return const Allow(); - } + switch (next.uri.path) { + // Block deep-link routes that should never render a page + // (we stay on the current page and show a lightweight UI instead). + case '/referral': + { + final String? code = next.uri.queryParameters['code']; + if (code != null) { + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Processing referral code...'), + duration: Duration(seconds: 2), + ), + ); + } + // Do the real work in the background; don’t keep the user waiting. + await _processReferralCodeInBackground(context, code); + } + return const Block.stop(); // keep user where they are + } - // Demonstrate error reporting path - case '/crash-test': - throw Exception('Simulated error in onEnter callback!'); - - case '/protected': - { - // ignore: prefer_final_locals - bool isLoggedIn = false; // pretend we’re not authenticated - if (!isLoggedIn) { - // Chaining block: cancel the original nav, then redirect to /login. - // This preserves redirection history to detect loops. - final String from = Uri.encodeComponent(next.uri.toString()); - return Block.then(() => router.go('/login?from=$from')); - } - // ignore: dead_code - return const Allow(); - } + // Simulate an OAuth callback: do background work + toast; never show a page at /auth + case '/auth': + { + final String? token = next.uri.queryParameters['token']; + if (token != null) { + _handleAuthToken(context, token); + return const Block.stop(); // cancel showing any /auth page + } + return const Allow(); + } - default: - return const Allow(); - } - }, + // Demonstrate error reporting path + case '/crash-test': + throw Exception('Simulated error in onEnter callback!'); + + case '/protected': + { + // ignore: prefer_final_locals + bool isLoggedIn = false; // pretend we’re not authenticated + if (!isLoggedIn) { + // Chaining block: cancel the original nav, then redirect to /login. + // This preserves redirection history to detect loops. + final String from = Uri.encodeComponent( + next.uri.toString(), + ); + return Block.then(() => router.go('/login?from=$from')); + } + // ignore: dead_code + return const Allow(); + } + + default: + return const Allow(); + } + }, routes: [ // Simple “root → home” diff --git a/packages/go_router/example/lib/transition_animations.dart b/packages/go_router/example/lib/transition_animations.dart index 32b03f84017..96f93f1d9f8 100644 --- a/packages/go_router/example/lib/transition_animations.dart +++ b/packages/go_router/example/lib/transition_animations.dart @@ -29,21 +29,22 @@ final GoRouter _router = GoRouter( key: state.pageKey, child: const DetailsScreen(), transitionDuration: const Duration(milliseconds: 150), - transitionsBuilder: ( - BuildContext context, - Animation animation, - Animation secondaryAnimation, - Widget child, - ) { - // Change the opacity of the screen using a Curve based on the the animation's - // value - return FadeTransition( - opacity: CurveTween( - curve: Curves.easeInOut, - ).animate(animation), - child: child, - ); - }, + transitionsBuilder: + ( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + Widget child, + ) { + // Change the opacity of the screen using a Curve based on the the animation's + // value + return FadeTransition( + opacity: CurveTween( + curve: Curves.easeInOut, + ).animate(animation), + child: child, + ); + }, ); }, ), @@ -72,14 +73,15 @@ final GoRouter _router = GoRouter( opaque: false, transitionDuration: const Duration(milliseconds: 500), reverseTransitionDuration: const Duration(milliseconds: 200), - transitionsBuilder: ( - BuildContext context, - Animation animation, - Animation secondaryAnimation, - Widget child, - ) { - return FadeTransition(opacity: animation, child: child); - }, + transitionsBuilder: + ( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + Widget child, + ) { + return FadeTransition(opacity: animation, child: child); + }, ); }, ), @@ -123,8 +125,8 @@ class HomeScreen extends StatelessWidget { ), const SizedBox(height: 48), ElevatedButton( - onPressed: - () => context.go('/custom-reverse-transition-duration'), + onPressed: () => + context.go('/custom-reverse-transition-duration'), child: const Text( 'Go to the Custom Reverse Transition Duration Screen', ), diff --git a/packages/go_router/example/pubspec.yaml b/packages/go_router/example/pubspec.yaml index 056e9de8271..8d812824b7d 100644 --- a/packages/go_router/example/pubspec.yaml +++ b/packages/go_router/example/pubspec.yaml @@ -4,8 +4,8 @@ version: 3.0.1 publish_to: none environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: adaptive_navigation: ^0.0.4 diff --git a/packages/go_router/lib/src/builder.dart b/packages/go_router/lib/src/builder.dart index 5eb0466cef4..dd6f89f10f3 100644 --- a/packages/go_router/lib/src/builder.dart +++ b/packages/go_router/lib/src/builder.dart @@ -286,36 +286,37 @@ class _CustomNavigatorState extends State<_CustomNavigator> { navigatorKey: navigatorKey, match: match, routeMatchList: widget.matchList, - navigatorBuilder: ( - GlobalKey navigatorKey, - ShellRouteMatch match, - RouteMatchList matchList, - List? observers, - String? restorationScopeId, - ) { - return PopScope( - // Prevent ShellRoute from being popped, for example - // by an iOS back gesture, when the route has active sub-routes. - // TODO(LukasMirbt): Remove when minimum flutter version includes - // https://github.com/flutter/flutter/pull/152330. - canPop: match.matches.length == 1, - child: _CustomNavigator( - // The state needs to persist across rebuild. - key: GlobalObjectKey(navigatorKey.hashCode), - navigatorRestorationId: restorationScopeId, - navigatorKey: navigatorKey, - matches: match.matches, - matchList: matchList, - configuration: widget.configuration, - observers: observers ?? const [], - onPopPageWithRouteMatch: widget.onPopPageWithRouteMatch, - // This is used to recursively build pages under this shell route. - errorBuilder: widget.errorBuilder, - errorPageBuilder: widget.errorPageBuilder, - requestFocus: widget.requestFocus, - ), - ); - }, + navigatorBuilder: + ( + GlobalKey navigatorKey, + ShellRouteMatch match, + RouteMatchList matchList, + List? observers, + String? restorationScopeId, + ) { + return PopScope( + // Prevent ShellRoute from being popped, for example + // by an iOS back gesture, when the route has active sub-routes. + // TODO(LukasMirbt): Remove when minimum flutter version includes + // https://github.com/flutter/flutter/pull/152330. + canPop: match.matches.length == 1, + child: _CustomNavigator( + // The state needs to persist across rebuild. + key: GlobalObjectKey(navigatorKey.hashCode), + navigatorRestorationId: restorationScopeId, + navigatorKey: navigatorKey, + matches: match.matches, + matchList: matchList, + configuration: widget.configuration, + observers: observers ?? const [], + onPopPageWithRouteMatch: widget.onPopPageWithRouteMatch, + // This is used to recursively build pages under this shell route. + errorBuilder: widget.errorBuilder, + errorPageBuilder: widget.errorPageBuilder, + requestFocus: widget.requestFocus, + ), + ); + }, ); final Page? page = match.route.buildPage( context, @@ -353,13 +354,13 @@ class _CustomNavigatorState extends State<_CustomNavigator> { if (elem != null && isMaterialApp(elem)) { log('Using MaterialApp configuration'); _pageBuilderForAppType = pageBuilderForMaterialApp; - _errorBuilderForAppType = - (BuildContext c, GoRouterState s) => MaterialErrorScreen(s.error); + _errorBuilderForAppType = (BuildContext c, GoRouterState s) => + MaterialErrorScreen(s.error); } else if (elem != null && isCupertinoApp(elem)) { log('Using CupertinoApp configuration'); _pageBuilderForAppType = pageBuilderForCupertinoApp; - _errorBuilderForAppType = - (BuildContext c, GoRouterState s) => CupertinoErrorScreen(s.error); + _errorBuilderForAppType = (BuildContext c, GoRouterState s) => + CupertinoErrorScreen(s.error); } else { log('Using WidgetsApp configuration'); _pageBuilderForAppType = @@ -376,8 +377,8 @@ class _CustomNavigatorState extends State<_CustomNavigator> { restorationId: restorationId, child: child, ); - _errorBuilderForAppType = - (BuildContext c, GoRouterState s) => ErrorScreen(s.error); + _errorBuilderForAppType = (BuildContext c, GoRouterState s) => + ErrorScreen(s.error); } } @@ -433,12 +434,12 @@ class _CustomNavigatorState extends State<_CustomNavigator> { return widget.errorPageBuilder != null ? widget.errorPageBuilder!(context, state) : _buildPlatformAdapterPage( - context, - state, - errorBuilder != null - ? errorBuilder(context, state) - : _errorBuilderForAppType!(context, state), - ); + context, + state, + errorBuilder != null + ? errorBuilder(context, state) + : _errorBuilderForAppType!(context, state), + ); } bool _handlePopPage(Route route, Object? result) { diff --git a/packages/go_router/lib/src/configuration.dart b/packages/go_router/lib/src/configuration.dart index 8e070a8d1cf..4a22c3e1c5f 100644 --- a/packages/go_router/lib/src/configuration.dart +++ b/packages/go_router/lib/src/configuration.dart @@ -144,10 +144,9 @@ class RouteConfiguration { // Recursively search for the first GoRoute descendant. Will // throw assertion error if not found. final GoRoute? defaultGoRoute = branch.defaultRoute; - final String? initialLocation = - defaultGoRoute != null - ? locationForRoute(defaultGoRoute) - : null; + final String? initialLocation = defaultGoRoute != null + ? locationForRoute(defaultGoRoute) + : null; assert( initialLocation != null, 'The default location of a StatefulShellBranch must be ' @@ -451,10 +450,9 @@ class RouteConfiguration { return routeLevelRedirectResult .then(processRouteLevelRedirect) .catchError((Object error) { - final GoException goException = - error is GoException - ? error - : GoException('Exception during route redirect: $error'); + final GoException goException = error is GoException + ? error + : GoException('Exception during route redirect: $error'); return _errorRouteMatchList( prevMatchList.uri, goException, @@ -462,10 +460,9 @@ class RouteConfiguration { ); }); } catch (exception) { - final GoException goException = - exception is GoException - ? exception - : GoException('Exception during route redirect: $exception'); + final GoException goException = exception is GoException + ? exception + : GoException('Exception during route redirect: $exception'); return _errorRouteMatchList( prevMatchList.uri, goException, @@ -519,10 +516,9 @@ class RouteConfiguration { return done(res); } return res.then(done).catchError((Object error) { - final GoException goException = - error is GoException - ? error - : GoException('Exception during redirect: $error'); + final GoException goException = error is GoException + ? error + : GoException('Exception during redirect: $error'); return _errorRouteMatchList( prevMatchList.uri, goException, @@ -530,10 +526,9 @@ class RouteConfiguration { ); }); } catch (exception) { - final GoException goException = - exception is GoException - ? exception - : GoException('Exception during redirect: $exception'); + final GoException goException = exception is GoException + ? exception + : GoException('Exception during redirect: $exception'); return _errorRouteMatchList( prevMatchList.uri, goException, @@ -571,20 +566,18 @@ class RouteConfiguration { return routeRedirectResult.then(processRouteRedirect).catchError( (Object error) { // Convert any exception during async route redirect to a GoException - final GoException goException = - error is GoException - ? error - : GoException('Exception during route redirect: $error'); + final GoException goException = error is GoException + ? error + : GoException('Exception during route redirect: $error'); // Throw the GoException to be caught by the redirect handling chain throw goException; }, ); } catch (exception) { // Convert any exception during route redirect to a GoException - final GoException goException = - exception is GoException - ? exception - : GoException('Exception during route redirect: $exception'); + final GoException goException = exception is GoException + ? exception + : GoException('Exception during route redirect: $exception'); // Throw the GoException to be caught by the redirect handling chain throw goException; } @@ -606,10 +599,9 @@ class RouteConfiguration { } return newMatch; } catch (exception) { - final GoException goException = - exception is GoException - ? exception - : GoException('Exception during redirect: $exception'); + final GoException goException = exception is GoException + ? exception + : GoException('Exception during redirect: $exception'); log('Redirection exception: ${goException.message}'); return _errorRouteMatchList(previousLocation, goException); } @@ -660,10 +652,9 @@ class RouteConfiguration { (Object error, StackTrace stack) { errorOccurred = true; // Convert any exception during redirect to a GoException and rethrow - final GoException goException = - error is GoException - ? error - : GoException('Exception during redirect: $error'); + final GoException goException = error is GoException + ? error + : GoException('Exception during redirect: $error'); throw goException; }, zoneValues: {currentRouterKey: router}, @@ -728,13 +719,16 @@ class RouteConfiguration { index, routes.length, ); - final String decorationString = - decoration.map((_DecorationType e) => e.toString()).join(); + final String decorationString = decoration + .map((_DecorationType e) => e.toString()) + .join(); String path = parentFullpath; if (route is GoRoute) { path = concatenatePaths(parentFullpath, route.path); - final String? screenName = - route.builder?.runtimeType.toString().split('=> ').last; + final String? screenName = route.builder?.runtimeType + .toString() + .split('=> ') + .last; sb.writeln( '$decorationString$path ' '${screenName == null ? '' : '($screenName)'}', diff --git a/packages/go_router/lib/src/delegate.dart b/packages/go_router/lib/src/delegate.dart index ef27d8be90e..229c9865b1a 100644 --- a/packages/go_router/lib/src/delegate.dart +++ b/packages/go_router/lib/src/delegate.dart @@ -258,8 +258,9 @@ class GoRouterDelegate extends RouterDelegate } if (indexOfFirstDiff < currentGoRouteMatches.length) { - final List exitingMatches = - currentGoRouteMatches.sublist(indexOfFirstDiff).toList(); + final List exitingMatches = currentGoRouteMatches + .sublist(indexOfFirstDiff) + .toList(); return _callOnExitStartsAt( exitingMatches.length - 1, context: navigatorContext, diff --git a/packages/go_router/lib/src/match.dart b/packages/go_router/lib/src/match.dart index 27d843b1e47..b8ddbaac9c2 100644 --- a/packages/go_router/lib/src/match.dart +++ b/packages/go_router/lib/src/match.dart @@ -127,8 +127,9 @@ abstract class RouteMatchBase with Diagnosticable { // Grab the route matches for the scope navigator key and put it into the // matches for `null`. if (result.containsKey(scopedNavigatorKey)) { - final List matchesForScopedNavigator = - result.remove(scopedNavigatorKey)!; + final List matchesForScopedNavigator = result.remove( + scopedNavigatorKey, + )!; assert(matchesForScopedNavigator.isNotEmpty); result .putIfAbsent(null, () => []) @@ -149,8 +150,8 @@ abstract class RouteMatchBase with Diagnosticable { }) { final GlobalKey? parentKey = route.parentNavigatorKey == scopedNavigatorKey - ? null - : route.parentNavigatorKey; + ? null + : route.parentNavigatorKey; Map?, List>? subRouteMatches; late GlobalKey navigatorKeyUsed; for (final RouteBase subRoute in route.routes) { @@ -202,8 +203,8 @@ abstract class RouteMatchBase with Diagnosticable { }) { final GlobalKey? parentKey = route.parentNavigatorKey == scopedNavigatorKey - ? null - : route.parentNavigatorKey; + ? null + : route.parentNavigatorKey; final RegExpMatch? regExpMatch = route.matchPatternAsPrefix( remainingLocation, diff --git a/packages/go_router/lib/src/parser.dart b/packages/go_router/lib/src/parser.dart index 94ed9cb1d61..288682d1603 100644 --- a/packages/go_router/lib/src/parser.dart +++ b/packages/go_router/lib/src/parser.dart @@ -172,10 +172,9 @@ class GoRouteInformationParser extends RouteInformationParser { ), extra: infoState.extra, ); - final RouteMatchList resolved = - onParserException != null - ? onParserException!(context, blocked) - : blocked; + final RouteMatchList resolved = onParserException != null + ? onParserException!(context, blocked) + : blocked; return SynchronousFuture(resolved); }, ); @@ -226,40 +225,41 @@ class GoRouteInformationParser extends RouteInformationParser { // Only route-level redirects from here on out. final FutureOr redirected = afterRouteLevel(baseMatches); - return debugParserFuture = (redirected is RouteMatchList - ? SynchronousFuture(redirected) - : redirected) - .then((RouteMatchList matchList) { - if (matchList.isError && onParserException != null) { - if (!context.mounted) { - return matchList; - } - return onParserException!(context, matchList); - } - - // Validate that redirect-only routes actually perform a redirection. - assert(() { - if (matchList.isNotEmpty) { - assert( - !matchList.last.route.redirectOnly, - 'A redirect-only route must redirect to location different from itself.\n The offending route: ${matchList.last.route}', + return debugParserFuture = + (redirected is RouteMatchList + ? SynchronousFuture(redirected) + : redirected) + .then((RouteMatchList matchList) { + if (matchList.isError && onParserException != null) { + if (!context.mounted) { + return matchList; + } + return onParserException!(context, matchList); + } + + // Validate that redirect-only routes actually perform a redirection. + assert(() { + if (matchList.isNotEmpty) { + assert( + !matchList.last.route.redirectOnly, + 'A redirect-only route must redirect to location different from itself.\n The offending route: ${matchList.last.route}', + ); + } + return true; + }()); + + // Update the route match list based on the navigation type. + final RouteMatchList updated = _updateRouteMatchList( + matchList, + baseRouteMatchList: infoState.baseRouteMatchList, + completer: infoState.completer, + type: infoState.type, ); - } - return true; - }()); - - // Update the route match list based on the navigation type. - final RouteMatchList updated = _updateRouteMatchList( - matchList, - baseRouteMatchList: infoState.baseRouteMatchList, - completer: infoState.completer, - type: infoState.type, - ); - // Cache the successful match list. - _lastMatchList = updated; - return updated; - }); + // Cache the successful match list. + _lastMatchList = updated; + return updated; + }); } @override @@ -459,10 +459,9 @@ class _OnEnterHandler { // Get the current state from the router delegate. final RouteMatchList currentMatchList = _router.routerDelegate.currentConfiguration; - final GoRouterState currentState = - currentMatchList.isNotEmpty - ? _buildTopLevelGoRouterState(currentMatchList) - : nextState; + final GoRouterState currentState = currentMatchList.isNotEmpty + ? _buildTopLevelGoRouterState(currentMatchList) + : nextState; // Execute the onEnter callback in a try-catch to capture synchronous exceptions. Future onEnterResultFuture; @@ -474,10 +473,9 @@ class _OnEnterHandler { _router, ); // Convert FutureOr to Future - onEnterResultFuture = - result is OnEnterResult - ? SynchronousFuture(result) - : result; + onEnterResultFuture = result is OnEnterResult + ? SynchronousFuture(result) + : result; } catch (error) { final RouteMatchList errorMatchList = _errorRouteMatchList( routeInformation.uri, @@ -489,10 +487,9 @@ class _OnEnterHandler { final bool canHandleException = _onParserException != null && context.mounted; - final RouteMatchList handledMatchList = - canHandleException - ? _onParserException(context, errorMatchList) - : errorMatchList; + final RouteMatchList handledMatchList = canHandleException + ? _onParserException(context, errorMatchList) + : errorMatchList; return SynchronousFuture(handledMatchList); } diff --git a/packages/go_router/lib/src/path_utils.dart b/packages/go_router/lib/src/path_utils.dart index d9d961c856f..29aec2c475f 100644 --- a/packages/go_router/lib/src/path_utils.dart +++ b/packages/go_router/lib/src/path_utils.dart @@ -36,10 +36,9 @@ RegExp patternToRegExp( } final String name = match[1]!; final String? optionalPattern = match[2]; - final String regex = - optionalPattern != null - ? _escapeGroup(optionalPattern, name) - : '(?<$name>[^/]+)'; + final String regex = optionalPattern != null + ? _escapeGroup(optionalPattern, name) + : '(?<$name>[^/]+)'; buffer.write(regex); parameters.add(name); start = match.end; @@ -150,21 +149,20 @@ String canonicalUri(String loc) { // /login?from=/ => /login?from=/ canon = uri.path.endsWith('/') && - uri.path != '/' && - !uri.hasQuery && - !uri.hasFragment - ? canon.substring(0, canon.length - 1) - : canon; + uri.path != '/' && + !uri.hasQuery && + !uri.hasFragment + ? canon.substring(0, canon.length - 1) + : canon; // replace '/?', except for first occurrence, from path only // /login/?from=/ => /login?from=/ // /?from=/ => /?from=/ - final int pathStartIndex = - uri.host.isNotEmpty - ? uri.toString().indexOf(uri.host) + uri.host.length - : uri.hasScheme - ? uri.toString().indexOf(uri.scheme) + uri.scheme.length - : 0; + final int pathStartIndex = uri.host.isNotEmpty + ? uri.toString().indexOf(uri.host) + uri.host.length + : uri.hasScheme + ? uri.toString().indexOf(uri.scheme) + uri.scheme.length + : 0; if (pathStartIndex < canon.length) { canon = canon.replaceFirst('/?', '?', pathStartIndex + 1); } @@ -179,10 +177,9 @@ String? fullPathForRoute( List routes, ) { for (final RouteBase route in routes) { - final String fullPath = - (route is GoRoute) - ? concatenatePaths(parentFullpath, route.path) - : parentFullpath; + final String fullPath = (route is GoRoute) + ? concatenatePaths(parentFullpath, route.path) + : parentFullpath; if (route == targetRoute) { return fullPath; diff --git a/packages/go_router/lib/src/route.dart b/packages/go_router/lib/src/route.dart index 6d66ed79185..7a2a07db385 100644 --- a/packages/go_router/lib/src/route.dart +++ b/packages/go_router/lib/src/route.dart @@ -596,8 +596,9 @@ class ShellRouteContext { ]; if (notifyRootObserver) { - final List? rootObservers = - GoRouter.maybeOf(context)?.observers; + final List? rootObservers = GoRouter.maybeOf( + context, + )?.observers; if (rootObservers != null) { effectiveObservers.add(_MergedNavigatorObserver(rootObservers)); } @@ -1330,8 +1331,8 @@ class StatefulNavigationShell extends StatefulWidget { /// Gets the state for the nearest stateful shell route in the Widget tree. static StatefulNavigationShellState of(BuildContext context) { - final StatefulNavigationShellState? shellState = - context.findAncestorStateOfType(); + final StatefulNavigationShellState? shellState = context + .findAncestorStateOfType(); assert(shellState != null); return shellState!; } @@ -1340,8 +1341,8 @@ class StatefulNavigationShell extends StatefulWidget { /// /// Returns null if no stateful shell route is found. static StatefulNavigationShellState? maybeOf(BuildContext context) { - final StatefulNavigationShellState? shellState = - context.findAncestorStateOfType(); + final StatefulNavigationShellState? shellState = context + .findAncestorStateOfType(); return shellState; } @@ -1525,8 +1526,9 @@ class StatefulNavigationShellState extends State /// the branch (see [StatefulShellBranch.initialLocation]). void goBranch(int index, {bool initialLocation = false}) { assert(index >= 0 && index < route.branches.length); - final RouteMatchList? matchList = - initialLocation ? null : _matchListForBranch(index); + final RouteMatchList? matchList = initialLocation + ? null + : _matchListForBranch(index); if (matchList != null && matchList.isNotEmpty) { _router.restore(matchList); } else { @@ -1561,18 +1563,16 @@ class StatefulNavigationShellState extends State @override Widget build(BuildContext context) { - final List children = - route.branches - .map( - (StatefulShellBranch branch) => _BranchNavigatorProxy( - key: ObjectKey(branch), - branch: branch, - navigatorForBranch: - (StatefulShellBranch branch) => - _branchState[branch]?.navigator, - ), - ) - .toList(); + final List children = route.branches + .map( + (StatefulShellBranch branch) => _BranchNavigatorProxy( + key: ObjectKey(branch), + branch: branch, + navigatorForBranch: (StatefulShellBranch branch) => + _branchState[branch]?.navigator, + ), + ) + .toList(); return widget.containerBuilder(context, widget, children); } @@ -1682,16 +1682,12 @@ class _IndexedStackedRouteBranchContainer extends StatelessWidget { @override Widget build(BuildContext context) { - final List stackItems = - children - .mapIndexed( - (int index, Widget child) => _buildRouteBranchContainer( - context, - currentIndex == index, - child, - ), - ) - .toList(); + final List stackItems = children + .mapIndexed( + (int index, Widget child) => + _buildRouteBranchContainer(context, currentIndex == index, child), + ) + .toList(); return IndexedStack(index: currentIndex, children: stackItems); } diff --git a/packages/go_router/lib/src/route_data.dart b/packages/go_router/lib/src/route_data.dart index 9a8f3bf8e7e..dfbd9cced43 100644 --- a/packages/go_router/lib/src/route_data.dart +++ b/packages/go_router/lib/src/route_data.dart @@ -117,18 +117,14 @@ _GoRouteParameters _createGoRouteParameters({ } return _GoRouteParameters( - builder: - (BuildContext context, GoRouterState state) => - factoryImpl(state).build(context, state), - pageBuilder: - (BuildContext context, GoRouterState state) => - factoryImpl(state).buildPage(context, state), - redirect: - (BuildContext context, GoRouterState state) => - factoryImpl(state).redirect(context, state), - onExit: - (BuildContext context, GoRouterState state) => - factoryImpl(state).onExit(context, state), + builder: (BuildContext context, GoRouterState state) => + factoryImpl(state).build(context, state), + pageBuilder: (BuildContext context, GoRouterState state) => + factoryImpl(state).buildPage(context, state), + redirect: (BuildContext context, GoRouterState state) => + factoryImpl(state).redirect(context, state), + onExit: (BuildContext context, GoRouterState state) => + factoryImpl(state).onExit(context, state), ); } @@ -382,10 +378,9 @@ abstract class StatefulShellRouteData extends RouteData { BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell, - ) => - throw UnimplementedError( - 'One of `builder` or `pageBuilder` must be implemented.', - ); + ) => throw UnimplementedError( + 'One of `builder` or `pageBuilder` must be implemented.', + ); /// A helper function used by generated code. /// diff --git a/packages/go_router/lib/src/router.dart b/packages/go_router/lib/src/router.dart index 155e1c62bdb..b0a1971d5ad 100644 --- a/packages/go_router/lib/src/router.dart +++ b/packages/go_router/lib/src/router.dart @@ -272,18 +272,16 @@ class GoRouter implements RouterConfig { final ParserExceptionHandler? parserExceptionHandler; if (onException != null) { - parserExceptionHandler = ( - BuildContext context, - RouteMatchList routeMatchList, - ) { - onException( - context, - configuration.buildTopLevelGoRouterState(routeMatchList), - this, - ); - // Avoid updating GoRouterDelegate if onException is provided. - return routerDelegate.currentConfiguration; - }; + parserExceptionHandler = + (BuildContext context, RouteMatchList routeMatchList) { + onException( + context, + configuration.buildTopLevelGoRouterState(routeMatchList), + this, + ); + // Avoid updating GoRouterDelegate if onException is provided. + return routerDelegate.currentConfiguration; + }; } else { parserExceptionHandler = null; } @@ -311,9 +309,8 @@ class GoRouter implements RouterConfig { requestFocus: requestFocus, // wrap the returned Navigator to enable GoRouter.of(context).go() et al, // allowing the caller to wrap the navigator themselves - builderWithNav: - (BuildContext context, Widget child) => - InheritedGoRouter(goRouter: this, child: child), + builderWithNav: (BuildContext context, Widget child) => + InheritedGoRouter(goRouter: this, child: child), ); assert(() { @@ -439,16 +436,16 @@ class GoRouter implements RouterConfig { Object? extra, String? fragment, }) => - // Construct location with optional fragment - go( - namedLocation( - name, - pathParameters: pathParameters, - queryParameters: queryParameters, - fragment: fragment, - ), - extra: extra, - ); + // Construct location with optional fragment + go( + namedLocation( + name, + pathParameters: pathParameters, + queryParameters: queryParameters, + fragment: fragment, + ), + extra: extra, + ); /// Push a URI location onto the page stack w/ optional query parameters, e.g. /// `/family/f2/person/p1?color=blue`. diff --git a/packages/go_router/lib/src/state.dart b/packages/go_router/lib/src/state.dart index 269eb320223..b9db0e561ae 100644 --- a/packages/go_router/lib/src/state.dart +++ b/packages/go_router/lib/src/state.dart @@ -125,11 +125,8 @@ class GoRouterState { } final RouteSettings settings = route.settings; if (settings is Page) { - scope = - context - .dependOnInheritedWidgetOfExactType< - GoRouterStateRegistryScope - >(); + scope = context + .dependOnInheritedWidgetOfExactType(); if (scope == null) { throw _noGoRouterStateError; } @@ -252,8 +249,9 @@ class GoRouterStateRegistry extends ChangeNotifier { route.completed.then((Object? result) { // Can't use `page` directly because Route.settings may have changed during // the lifetime of this route. - final Page associatedPage = - _routePageAssociation.remove(route)!; + final Page associatedPage = _routePageAssociation.remove( + route, + )!; assert(registry.containsKey(associatedPage)); registry.remove(associatedPage); }); @@ -270,8 +268,8 @@ class GoRouterStateRegistry extends ChangeNotifier { /// Updates this registry with new records. void updateRegistry(Map, GoRouterState> newRegistry) { bool shouldNotify = false; - final Set> pagesWithAssociation = - _routePageAssociation.values.toSet(); + final Set> pagesWithAssociation = _routePageAssociation.values + .toSet(); for (final MapEntry, GoRouterState> entry in newRegistry.entries) { final GoRouterState? existingState = registry[entry.key]; diff --git a/packages/go_router/pubspec.yaml b/packages/go_router/pubspec.yaml index a65ff345c7d..cf88637eef5 100644 --- a/packages/go_router/pubspec.yaml +++ b/packages/go_router/pubspec.yaml @@ -6,8 +6,8 @@ repository: https://github.com/flutter/packages/tree/main/packages/go_router issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+go_router%22 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: collection: ^1.15.0 diff --git a/packages/go_router/test/builder_test.dart b/packages/go_router/test/builder_test.dart index 7e496979d9a..66cc2d58920 100644 --- a/packages/go_router/test/builder_test.dart +++ b/packages/go_router/test/builder_test.dart @@ -381,9 +381,8 @@ void main() { routes: [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => - const Scaffold(body: Center(child: Text('Home'))), + builder: (BuildContext context, GoRouterState state) => + const Scaffold(body: Center(child: Text('Home'))), ), ], ); @@ -405,9 +404,8 @@ void main() { routes: [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => - const Scaffold(body: Center(child: Text('Home'))), + builder: (BuildContext context, GoRouterState state) => + const Scaffold(body: Center(child: Text('Home'))), ), ], requestFocus: false, @@ -434,7 +432,10 @@ class _HomeScreen extends StatelessWidget { Widget build(BuildContext context) { return Scaffold( body: Column( - children: [const Text('Home Screen'), Expanded(child: child)], + children: [ + const Text('Home Screen'), + Expanded(child: child), + ], ), ); } diff --git a/packages/go_router/test/custom_transition_page_test.dart b/packages/go_router/test/custom_transition_page_test.dart index 71e11415b68..9f4c765d357 100644 --- a/packages/go_router/test/custom_transition_page_test.dart +++ b/packages/go_router/test/custom_transition_page_test.dart @@ -118,16 +118,18 @@ void main() { final GoRouter router = GoRouter( routes: [ - GoRoute(path: '/', builder: (_, __) => const HomeScreen(key: homeKey)), + GoRoute( + path: '/', + builder: (_, __) => const HomeScreen(key: homeKey), + ), GoRoute( path: '/dismissible-modal', - pageBuilder: - (_, GoRouterState state) => CustomTransitionPage( - key: state.pageKey, - barrierDismissible: true, - transitionsBuilder: (_, __, ___, Widget child) => child, - child: const DismissibleModal(key: dismissibleModalKey), - ), + pageBuilder: (_, GoRouterState state) => CustomTransitionPage( + key: state.pageKey, + barrierDismissible: true, + transitionsBuilder: (_, __, ___, Widget child) => child, + child: const DismissibleModal(key: dismissibleModalKey), + ), ), ], ); @@ -152,19 +154,21 @@ void main() { final GoRouter router = GoRouter( routes: [ - GoRoute(path: '/', builder: (_, __) => const HomeScreen(key: homeKey)), + GoRoute( + path: '/', + builder: (_, __) => const HomeScreen(key: homeKey), + ), GoRoute( path: '/login', - pageBuilder: - (_, GoRouterState state) => CustomTransitionPage( - key: state.pageKey, - transitionDuration: transitionDuration, - reverseTransitionDuration: reverseTransitionDuration, - transitionsBuilder: - (_, Animation animation, ___, Widget child) => - FadeTransition(opacity: animation, child: child), - child: const LoginScreen(key: loginKey), - ), + pageBuilder: (_, GoRouterState state) => CustomTransitionPage( + key: state.pageKey, + transitionDuration: transitionDuration, + reverseTransitionDuration: reverseTransitionDuration, + transitionsBuilder: + (_, Animation animation, ___, Widget child) => + FadeTransition(opacity: animation, child: child), + child: const LoginScreen(key: loginKey), + ), ), ], ); diff --git a/packages/go_router/test/delegate_test.dart b/packages/go_router/test/delegate_test.dart index f523c7d44ea..ae85f7cca1d 100644 --- a/packages/go_router/test/delegate_test.dart +++ b/packages/go_router/test/delegate_test.dart @@ -100,21 +100,19 @@ Future createGoRouterWithStatefulShellRouteAndPopScopes( routes: [ GoRoute( path: '/c', - builder: - (_, __) => PopScope( - onPopInvokedWithResult: onPopBranch, - canPop: canPopBranch, - child: const Text('Home'), - ), + builder: (_, __) => PopScope( + onPopInvokedWithResult: onPopBranch, + canPop: canPopBranch, + child: const Text('Home'), + ), routes: [ GoRoute( path: 'c1', - builder: - (_, __) => PopScope( - onPopInvokedWithResult: onPopBranchSubRoute, - canPop: canPopBranchSubRoute, - child: const Text('SubRoute'), - ), + builder: (_, __) => PopScope( + onPopInvokedWithResult: onPopBranchSubRoute, + canPop: canPopBranchSubRoute, + child: const Text('SubRoute'), + ), ), ], ), @@ -197,14 +195,13 @@ void main() { routes: [ GoRoute( path: '/', - builder: - (_, __) => PopScope( - onPopInvokedWithResult: (bool result, _) { - didPop = true; - }, - canPop: false, - child: const Text('Home'), - ), + builder: (_, __) => PopScope( + onPopInvokedWithResult: (bool result, _) { + didPop = true; + }, + canPop: false, + child: const Text('Home'), + ), ), ], ); diff --git a/packages/go_router/test/exception_handling_test.dart b/packages/go_router/test/exception_handling_test.dart index 2aca1f9f3ca..f24b48075b5 100644 --- a/packages/go_router/test/exception_handling_test.dart +++ b/packages/go_router/test/exception_handling_test.dart @@ -70,14 +70,13 @@ void main() { [ GoRoute( path: '/error', - builder: - (_, GoRouterState state) => Text('redirected ${state.extra}'), + builder: (_, GoRouterState state) => + Text('redirected ${state.extra}'), ), ], tester, - onException: - (_, GoRouterState state, GoRouter router) => - router.go('/error', extra: state.uri.toString()), + onException: (_, GoRouterState state, GoRouter router) => + router.go('/error', extra: state.uri.toString()), ); expect(find.text('redirected /'), findsOneWidget); @@ -95,9 +94,8 @@ void main() { ), ], tester, - onException: - (_, GoRouterState state, GoRouter router) => - router.go('/error', extra: state.extra), + onException: (_, GoRouterState state, GoRouter router) => + router.go('/error', extra: state.extra), ); expect(find.text('extra: null'), findsOneWidget); @@ -138,14 +136,13 @@ void main() { ), GoRoute( path: '/error-page', - builder: - (_, GoRouterState state) => - Text('error handled: ${state.extra}'), + builder: (_, GoRouterState state) => + Text('error handled: ${state.extra}'), ), GoRoute( path: '/trigger-error', - builder: - (_, GoRouterState state) => const Text('should not reach here'), + builder: (_, GoRouterState state) => + const Text('should not reach here'), ), ], tester, @@ -156,15 +153,12 @@ void main() { } return null; }, - onException: ( - BuildContext context, - GoRouterState state, - GoRouter router, - ) { - exceptionCaught = true; - errorMessage = 'Caught exception for ${state.uri}'; - router.go('/error-page', extra: errorMessage); - }, + onException: + (BuildContext context, GoRouterState state, GoRouter router) { + exceptionCaught = true; + errorMessage = 'Caught exception for ${state.uri}'; + router.go('/error-page', extra: errorMessage); + }, ); expect(find.text('home'), findsOneWidget); @@ -197,13 +191,13 @@ void main() { ), GoRoute( path: '/error-page', - builder: - (_, GoRouterState state) => const Text('generic error handled'), + builder: (_, GoRouterState state) => + const Text('generic error handled'), ), GoRoute( path: '/trigger-runtime-error', - builder: - (_, GoRouterState state) => const Text('should not reach here'), + builder: (_, GoRouterState state) => + const Text('should not reach here'), ), ], tester, @@ -214,14 +208,11 @@ void main() { } return null; }, - onException: ( - BuildContext context, - GoRouterState state, - GoRouter router, - ) { - exceptionCaught = true; - router.go('/error-page'); - }, + onException: + (BuildContext context, GoRouterState state, GoRouter router) { + exceptionCaught = true; + router.go('/error-page'); + }, ); expect(find.text('home'), findsOneWidget); diff --git a/packages/go_router/test/extension_test.dart b/packages/go_router/test/extension_test.dart index 4d36f5a5ade..9a28d17d4c7 100644 --- a/packages/go_router/test/extension_test.dart +++ b/packages/go_router/test/extension_test.dart @@ -52,12 +52,11 @@ class _MyWidget extends StatelessWidget { @override Widget build(BuildContext context) { return ElevatedButton( - onPressed: - () => context.replaceNamed( - 'page-0', - pathParameters: {'tab': 'settings'}, - queryParameters: {'search': 'notification'}, - ), + onPressed: () => context.replaceNamed( + 'page-0', + pathParameters: {'tab': 'settings'}, + queryParameters: {'search': 'notification'}, + ), child: const Text('Settings'), ); } diff --git a/packages/go_router/test/go_route_test.dart b/packages/go_router/test/go_route_test.dart index 785ce4d0b94..4ede231e47f 100644 --- a/packages/go_router/test/go_route_test.dart +++ b/packages/go_router/test/go_route_test.dart @@ -51,20 +51,17 @@ void main() { routes: [ ShellRoute( parentNavigatorKey: rootNavigatorKey, - builder: ( - BuildContext context, - GoRouterState state, - Widget child, - ) { - return Scaffold( - body: Column( - children: [ - const Text('Screen D'), - Expanded(child: child), - ], - ), - ); - }, + builder: + (BuildContext context, GoRouterState state, Widget child) { + return Scaffold( + body: Column( + children: [ + const Text('Screen D'), + Expanded(child: child), + ], + ), + ); + }, routes: [ GoRoute( path: 'c', @@ -261,9 +258,8 @@ void main() { routes: [ GoRoute( path: '1', - builder: - (_, __) => - const Text('/route/1'), // Renders "/route/1" text + builder: (_, __) => + const Text('/route/1'), // Renders "/route/1" text ), ], ), diff --git a/packages/go_router/test/go_router_state_test.dart b/packages/go_router/test/go_router_state_test.dart index 5e769e05d52..8d82976c14d 100644 --- a/packages/go_router/test/go_router_state_test.dart +++ b/packages/go_router/test/go_router_state_test.dart @@ -152,12 +152,11 @@ void main() { initialLocation: '/a', ); expect(tester.widget(find.byKey(key)).data, '/a'); - final GoRouterStateRegistry registry = - tester - .widget( - find.byType(GoRouterStateRegistryScope), - ) - .notifier!; + final GoRouterStateRegistry registry = tester + .widget( + find.byType(GoRouterStateRegistryScope), + ) + .notifier!; expect(registry.registry.length, 2); router.go('/'); await tester.pump(); @@ -207,12 +206,11 @@ void main() { navigatorKey: nav, ); expect(tester.widget(find.byKey(key)).data, '/a'); - final GoRouterStateRegistry registry = - tester - .widget( - find.byType(GoRouterStateRegistryScope), - ) - .notifier!; + final GoRouterStateRegistry registry = tester + .widget( + find.byType(GoRouterStateRegistryScope), + ) + .notifier!; expect(registry.registry.length, 2); nav.currentState!.pop(); await tester.pump(); @@ -292,25 +290,27 @@ void main() { routes: [ StatefulShellRoute.indexedStack( parentNavigatorKey: rootNavigatorKey, - builder: ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - final String? routeName = - GoRouterState.of(context).topRoute?.name; - final String title = switch (routeName) { - 'a' => 'A', - 'b' => 'B', - _ => 'Unknown', - }; - return Column( - children: [ - Text(title), - Expanded(child: navigationShell), - ], - ); - }, + builder: + ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + final String? routeName = GoRouterState.of( + context, + ).topRoute?.name; + final String title = switch (routeName) { + 'a' => 'A', + 'b' => 'B', + _ => 'Unknown', + }; + return Column( + children: [ + Text(title), + Expanded(child: navigationShell), + ], + ); + }, branches: [ StatefulShellBranch( routes: [ diff --git a/packages/go_router/test/go_router_test.dart b/packages/go_router/test/go_router_test.dart index 0b4dc08e6fa..b77f6fc6f71 100644 --- a/packages/go_router/test/go_router_test.dart +++ b/packages/go_router/test/go_router_test.dart @@ -45,8 +45,8 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), ), ]; @@ -126,9 +126,8 @@ void main() { final GoRouter router = await createRouter( routes, tester, - errorBuilder: - (BuildContext context, GoRouterState state) => - TestErrorScreen(state.error!), + errorBuilder: (BuildContext context, GoRouterState state) => + TestErrorScreen(state.error!), ); router.go('/foo'); await tester.pumpAndSettle(); @@ -142,14 +141,13 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), ), GoRoute( path: '/login', - builder: - (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => + const LoginScreen(), ), ]; @@ -169,22 +167,20 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), routes: [ GoRoute( path: 'page1', - builder: - (BuildContext context, GoRouterState state) => - const Page1Screen(), + builder: (BuildContext context, GoRouterState state) => + const Page1Screen(), ), ], ), GoRoute( path: '/login', - builder: - (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => + const LoginScreen(), ), ]; @@ -204,14 +200,13 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), ), GoRoute( path: '/login', - builder: - (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => + const LoginScreen(), ), ]; @@ -275,9 +270,8 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), ), ]; @@ -298,15 +292,13 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), ), GoRoute( path: '/login', - builder: - (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => + const LoginScreen(), ), ]; @@ -376,7 +368,10 @@ void main() { final UniqueKey dialog = UniqueKey(); final GlobalKey navKey = GlobalKey(); final List routes = [ - GoRoute(path: '/', builder: (_, __) => DummyScreen(key: home)), + GoRoute( + path: '/', + builder: (_, __) => DummyScreen(key: home), + ), GoRoute( path: '/settings', builder: (_, __) => DummyScreen(key: settings), @@ -429,13 +424,12 @@ void main() { builder: (_, __) => const Text('home'), routes: [ ShellRoute( - builder: ( - BuildContext context, - GoRouterState state, - Widget child, - ) { - return Column(children: [const Text('shell'), child]); - }, + builder: + (BuildContext context, GoRouterState state, Widget child) { + return Column( + children: [const Text('shell'), child], + ); + }, routes: [ GoRoute( path: 'page', @@ -490,18 +484,18 @@ void main() { final List routes = [ GoRoute( path: '/', - pageBuilder: - (_, __) => const MaterialPage(child: HomeScreen()), + pageBuilder: (_, __) => + const MaterialPage(child: HomeScreen()), ), GoRoute( path: '/page1', - pageBuilder: - (_, __) => const MaterialPage(child: Page1Screen()), + pageBuilder: (_, __) => + const MaterialPage(child: Page1Screen()), ), GoRoute( path: '/page2', - pageBuilder: - (_, __) => const MaterialPage(child: Page2Screen()), + pageBuilder: (_, __) => + const MaterialPage(child: Page2Screen()), ), ]; final GoRouter router = await createRouter( @@ -536,14 +530,13 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), routes: [ GoRoute( path: 'login', - builder: - (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => + const LoginScreen(), ), ], ), @@ -565,28 +558,25 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), routes: [ GoRoute( path: 'family/:fid', - builder: - (BuildContext context, GoRouterState state) => - const FamilyScreen('dummy'), + builder: (BuildContext context, GoRouterState state) => + const FamilyScreen('dummy'), routes: [ GoRoute( path: 'person/:pid', - builder: - (BuildContext context, GoRouterState state) => - const PersonScreen('dummy', 'dummy'), + builder: (BuildContext context, GoRouterState state) => + const PersonScreen('dummy', 'dummy'), ), ], ), GoRoute( path: 'login', - builder: - (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => + const LoginScreen(), ), ], ), @@ -646,32 +636,28 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), routes: [ GoRoute( path: 'foo/bar', - builder: - (BuildContext context, GoRouterState state) => - const FamilyScreen(''), + builder: (BuildContext context, GoRouterState state) => + const FamilyScreen(''), ), GoRoute( path: 'bar', - builder: - (BuildContext context, GoRouterState state) => - const Page1Screen(), + builder: (BuildContext context, GoRouterState state) => + const Page1Screen(), ), GoRoute( path: 'foo', - builder: - (BuildContext context, GoRouterState state) => - const Page2Screen(), + builder: (BuildContext context, GoRouterState state) => + const Page2Screen(), routes: [ GoRoute( path: 'bar', - builder: - (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => + const LoginScreen(), ), ], ), @@ -794,15 +780,14 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), ), GoRoute( path: '/family/:fid', caseSensitive: false, - builder: - (BuildContext context, GoRouterState state) => - FamilyScreen(state.pathParameters['fid']!), + builder: (BuildContext context, GoRouterState state) => + FamilyScreen(state.pathParameters['fid']!), ), ]; @@ -829,14 +814,13 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), ), GoRoute( path: '/family/:fid', - builder: - (BuildContext context, GoRouterState state) => - FamilyScreen(state.pathParameters['fid']!), + builder: (BuildContext context, GoRouterState state) => + FamilyScreen(state.pathParameters['fid']!), ), ]; @@ -867,20 +851,18 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), ), GoRoute( path: '/abc', - builder: - (BuildContext context, GoRouterState state) => - const SizedBox(key: Key('abc')), + builder: (BuildContext context, GoRouterState state) => + const SizedBox(key: Key('abc')), ), GoRoute( path: '/ABC', - builder: - (BuildContext context, GoRouterState state) => - const SizedBox(key: Key('ABC')), + builder: (BuildContext context, GoRouterState state) => + const SizedBox(key: Key('ABC')), ), ]; @@ -1150,11 +1132,10 @@ void main() { GoRoute( path: '/', pageBuilder: (BuildContext context, GoRouterState state) { - final String value = - context - .dependOnInheritedWidgetOfExactType()! - .notifier! - .value; + final String value = context + .dependOnInheritedWidgetOfExactType()! + .notifier! + .value; return MaterialPage(key: state.pageKey, child: Text(value)); }, ), @@ -1219,16 +1200,17 @@ void main() { routes: [ ShellRoute( navigatorKey: shellNavigatorKeyB, - builder: ( - BuildContext context, - GoRouterState state, - Widget child, - ) { - return Scaffold( - appBar: AppBar(title: const Text('Shell')), - body: child, - ); - }, + builder: + ( + BuildContext context, + GoRouterState state, + Widget child, + ) { + return Scaffold( + appBar: AppBar(title: const Text('Shell')), + body: child, + ); + }, routes: [ GoRoute( path: 'b', @@ -1297,9 +1279,8 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => + const DummyScreen(), routes: [ ShellRoute( builder: @@ -1308,9 +1289,8 @@ void main() { routes: [ GoRoute( path: 'c', - builder: - (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => + const DummyScreen(), ), ], ), @@ -1547,13 +1527,10 @@ void main() { }, routes: [ ShellRoute( - builder: ( - BuildContext context, - GoRouterState state, - Widget child, - ) { - return Scaffold(appBar: AppBar(), body: child); - }, + builder: + (BuildContext context, GoRouterState state, Widget child) { + return Scaffold(appBar: AppBar(), body: child); + }, routes: [ GoRoute( path: 'b', @@ -1619,10 +1596,8 @@ void main() { routes: [ GoRoute( path: 'settings', - builder: - (_, GoRouterState state) => DummyScreen( - key: ValueKey('settings-${state.extra}'), - ), + builder: (_, GoRouterState state) => + DummyScreen(key: ValueKey('settings-${state.extra}')), ), ], ), @@ -1675,7 +1650,10 @@ void main() { final UniqueKey login = UniqueKey(); final List routes = [ GoRoute(path: '/', builder: (_, __) => const DummyScreen()), - GoRoute(path: '/login', builder: (_, __) => DummyScreen(key: login)), + GoRoute( + path: '/login', + builder: (_, __) => DummyScreen(key: login), + ), ]; final Completer completer = Completer(); final GoRouter router = await createRouter( @@ -1716,8 +1694,8 @@ void main() { GoRoute( name: 'home', path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), ), ]; @@ -1757,15 +1735,14 @@ void main() { GoRoute( name: 'home', path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), ), GoRoute( name: 'login', path: '/login', - builder: - (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => + const LoginScreen(), ), ]; @@ -1778,15 +1755,14 @@ void main() { GoRoute( name: 'home', path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), routes: [ GoRoute( name: 'login', path: 'login', - builder: - (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => + const LoginScreen(), ), ], ), @@ -1801,15 +1777,14 @@ void main() { GoRoute( name: 'home', path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), routes: [ GoRoute( name: 'family', path: 'family/:fid', - builder: - (BuildContext context, GoRouterState state) => - const FamilyScreen('dummy'), + builder: (BuildContext context, GoRouterState state) => + const FamilyScreen('dummy'), routes: [ GoRoute( name: 'person', @@ -1840,22 +1815,20 @@ void main() { GoRoute( name: 'home', path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), routes: [ GoRoute( name: 'family', path: 'family/:fid', - builder: - (BuildContext context, GoRouterState state) => - const FamilyScreen('dummy'), + builder: (BuildContext context, GoRouterState state) => + const FamilyScreen('dummy'), routes: [ GoRoute( name: 'person', path: 'person/:pid', - builder: - (BuildContext context, GoRouterState state) => - const PersonScreen('dummy', 'dummy'), + builder: (BuildContext context, GoRouterState state) => + const PersonScreen('dummy', 'dummy'), ), ], ), @@ -1874,15 +1847,14 @@ void main() { GoRoute( name: 'home', path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), routes: [ GoRoute( name: 'family', path: 'family/:fid', - builder: - (BuildContext context, GoRouterState state) => - const FamilyScreen('dummy'), + builder: (BuildContext context, GoRouterState state) => + const FamilyScreen('dummy'), routes: [ GoRoute( name: 'PeRsOn', @@ -1915,9 +1887,8 @@ void main() { GoRoute( name: 'family', path: '/family/:fid', - builder: - (BuildContext context, GoRouterState state) => - const FamilyScreen('dummy'), + builder: (BuildContext context, GoRouterState state) => + const FamilyScreen('dummy'), ), ]; await expectLater(() async { @@ -1931,9 +1902,8 @@ void main() { GoRoute( name: 'family', path: '/family/:fid', - builder: - (BuildContext context, GoRouterState state) => - const FamilyScreen('dummy'), + builder: (BuildContext context, GoRouterState state) => + const FamilyScreen('dummy'), ), ]; await expectLater(() async { @@ -1950,15 +1920,14 @@ void main() { GoRoute(path: '/', builder: dummy, redirect: (_, __) => '/family/f2'), GoRoute( path: '/family/:fid', - builder: - (BuildContext context, GoRouterState state) => - FamilyScreen(state.pathParameters['fid']!), + builder: (BuildContext context, GoRouterState state) => + FamilyScreen(state.pathParameters['fid']!), routes: [ GoRoute( name: 'person', path: 'person:pid', - builder: - (BuildContext context, GoRouterState state) => PersonScreen( + builder: (BuildContext context, GoRouterState state) => + PersonScreen( state.pathParameters['fid']!, state.pathParameters['pid']!, ), @@ -2037,14 +2006,13 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), routes: [ GoRoute( path: 'login', - builder: - (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => + const LoginScreen(), ), ], ), @@ -2060,14 +2028,13 @@ void main() { final List routes = [ GoRoute( path: '/home', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), routes: [ GoRoute( path: 'login', - builder: - (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => + const LoginScreen(), ), ], ), @@ -2087,14 +2054,13 @@ void main() { final List routes = [ GoRoute( path: '/home', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), routes: [ GoRoute( path: 'family/:fid', - builder: - (BuildContext context, GoRouterState state) => - const FamilyScreen('dummy'), + builder: (BuildContext context, GoRouterState state) => + const FamilyScreen('dummy'), routes: [ GoRoute( name: 'person', @@ -2135,14 +2101,13 @@ void main() { final List routes = [ GoRoute( path: '/home', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), routes: [ GoRoute( path: 'family', - builder: - (BuildContext context, GoRouterState state) => - const FamilyScreen('dummy'), + builder: (BuildContext context, GoRouterState state) => + const FamilyScreen('dummy'), routes: [ GoRoute( path: 'person', @@ -2180,20 +2145,18 @@ void main() { final List routes = [ GoRoute( path: '/home', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), routes: [ GoRoute( path: 'family/:fid', - builder: - (BuildContext context, GoRouterState state) => - const FamilyScreen('dummy'), + builder: (BuildContext context, GoRouterState state) => + const FamilyScreen('dummy'), routes: [ GoRoute( path: 'person/:pid', - builder: - (BuildContext context, GoRouterState state) => - const PersonScreen('dummy', 'dummy'), + builder: (BuildContext context, GoRouterState state) => + const PersonScreen('dummy', 'dummy'), ), ], ), @@ -2205,9 +2168,8 @@ void main() { routes, tester, initialLocation: '/home', - errorBuilder: - (BuildContext context, GoRouterState state) => - TestErrorScreen(state.error!), + errorBuilder: (BuildContext context, GoRouterState state) => + TestErrorScreen(state.error!), ); router.go('./family/person/$pid'); await tester.pumpAndSettle(); @@ -2222,20 +2184,18 @@ void main() { final List routes = [ GoRoute( path: '/home', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), routes: [ GoRoute( path: 'family', - builder: - (BuildContext context, GoRouterState state) => - const FamilyScreen('dummy'), + builder: (BuildContext context, GoRouterState state) => + const FamilyScreen('dummy'), routes: [ GoRoute( path: 'person', - builder: - (BuildContext context, GoRouterState state) => - const PersonScreen('dummy', 'dummy'), + builder: (BuildContext context, GoRouterState state) => + const PersonScreen('dummy', 'dummy'), ), ], ), @@ -2247,9 +2207,8 @@ void main() { routes, tester, initialLocation: '/home', - errorBuilder: - (BuildContext context, GoRouterState state) => - TestErrorScreen(state.error!), + errorBuilder: (BuildContext context, GoRouterState state) => + TestErrorScreen(state.error!), ); router.go('person'); @@ -2322,11 +2281,10 @@ void main() { initialLocation: '/home', ); - final String loc = - Uri( - path: 'page1', - queryParameters: {'param1': param1}, - ).toString(); + final String loc = Uri( + path: 'page1', + queryParameters: {'param1': param1}, + ).toString(); router.go('./$loc'); await tester.pumpAndSettle(); @@ -2342,20 +2300,18 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), routes: [ GoRoute( path: 'dummy', - builder: - (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => + const DummyScreen(), ), GoRoute( path: 'login', - builder: - (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => + const LoginScreen(), ), ], ), @@ -2396,20 +2352,18 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), ), GoRoute( path: '/login', - builder: - (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => + const LoginScreen(), ), GoRoute( path: '/trigger-error', - builder: - (BuildContext context, GoRouterState state) => - const Text('should not reach here'), + builder: (BuildContext context, GoRouterState state) => + const Text('should not reach here'), ), ]; @@ -2422,13 +2376,10 @@ void main() { } return null; }, - onException: ( - BuildContext context, - GoRouterState state, - GoRouter router, - ) { - exceptionCaught = true; - }, + onException: + (BuildContext context, GoRouterState state, GoRouter router) { + exceptionCaught = true; + }, ); expect(find.byType(HomeScreen), findsOneWidget); @@ -2453,15 +2404,14 @@ void main() { GoRoute( path: '/', name: 'home', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), ), GoRoute( path: '/login', name: 'login', - builder: - (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => + const LoginScreen(), ), ]; @@ -2483,16 +2433,15 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), routes: [ GoRoute( path: 'dummy', // Return same location. redirect: (_, GoRouterState state) => state.uri.toString(), - builder: - (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => + const DummyScreen(), ), ], ), @@ -2524,22 +2473,20 @@ void main() { GoRoute( name: 'home', path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), routes: [ GoRoute( name: 'dummy', path: 'dummy', - builder: - (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => + const DummyScreen(), ), GoRoute( name: 'login', path: 'login', - builder: - (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => + const LoginScreen(), ), ], ), @@ -2548,11 +2495,10 @@ void main() { final GoRouter router = await createRouter( routes, tester, - redirect: - (BuildContext context, GoRouterState state) => - state.matchedLocation == '/login' - ? null - : state.namedLocation('login'), + redirect: (BuildContext context, GoRouterState state) => + state.matchedLocation == '/login' + ? null + : state.namedLocation('login'), ); expect( router.routerDelegate.currentConfiguration.uri.toString(), @@ -2564,21 +2510,19 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), routes: [ GoRoute( path: 'dummy', - builder: - (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => + const DummyScreen(), redirect: (BuildContext context, GoRouterState state) => '/login', ), GoRoute( path: 'login', - builder: - (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => + const LoginScreen(), ), ], ), @@ -2599,14 +2543,13 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), routes: [ GoRoute( path: 'dummy', - builder: - (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => + const DummyScreen(), redirect: (BuildContext context, GoRouterState state) { // should never be reached. assert(false); @@ -2615,15 +2558,13 @@ void main() { ), GoRoute( path: 'dummy2', - builder: - (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => + const DummyScreen(), ), GoRoute( path: 'login', - builder: - (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => + const LoginScreen(), ), ], ), @@ -2656,25 +2597,22 @@ void main() { GoRoute( name: 'home', path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), routes: [ GoRoute( name: 'dummy', path: 'dummy', - builder: - (BuildContext context, GoRouterState state) => - const DummyScreen(), - redirect: - (BuildContext context, GoRouterState state) => - state.namedLocation('login'), + builder: (BuildContext context, GoRouterState state) => + const DummyScreen(), + redirect: (BuildContext context, GoRouterState state) => + state.namedLocation('login'), ), GoRoute( name: 'login', path: 'login', - builder: - (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => + const LoginScreen(), ), ], ), @@ -2693,20 +2631,18 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), routes: [ GoRoute( path: 'dummy1', - builder: - (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => + const DummyScreen(), ), GoRoute( path: 'dummy2', - builder: - (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => + const DummyScreen(), redirect: (BuildContext context, GoRouterState state) => '/', ), ], @@ -2716,9 +2652,8 @@ void main() { final GoRouter router = await createRouter( routes, tester, - redirect: - (BuildContext context, GoRouterState state) => - state.matchedLocation == '/dummy1' ? '/dummy2' : null, + redirect: (BuildContext context, GoRouterState state) => + state.matchedLocation == '/dummy1' ? '/dummy2' : null, ); router.go('/dummy1'); await tester.pump(); @@ -2729,16 +2664,14 @@ void main() { final GoRouter router = await createRouter( [], tester, - redirect: - (BuildContext context, GoRouterState state) => - state.matchedLocation == '/' - ? '/login' - : state.matchedLocation == '/login' - ? '/' - : null, - errorBuilder: - (BuildContext context, GoRouterState state) => - TestErrorScreen(state.error!), + redirect: (BuildContext context, GoRouterState state) => + state.matchedLocation == '/' + ? '/login' + : state.matchedLocation == '/login' + ? '/' + : null, + errorBuilder: (BuildContext context, GoRouterState state) => + TestErrorScreen(state.error!), ); final List matches = router.routerDelegate.currentConfiguration.matches; @@ -2765,9 +2698,8 @@ void main() { ), ], tester, - errorBuilder: - (BuildContext context, GoRouterState state) => - TestErrorScreen(state.error!), + errorBuilder: (BuildContext context, GoRouterState state) => + TestErrorScreen(state.error!), ); final List matches = @@ -2790,12 +2722,10 @@ void main() { ), ], tester, - redirect: - (BuildContext context, GoRouterState state) => - state.matchedLocation == '/' ? '/login' : null, - errorBuilder: - (BuildContext context, GoRouterState state) => - TestErrorScreen(state.error!), + redirect: (BuildContext context, GoRouterState state) => + state.matchedLocation == '/' ? '/login' : null, + errorBuilder: (BuildContext context, GoRouterState state) => + TestErrorScreen(state.error!), ); final List matches = @@ -2814,16 +2744,14 @@ void main() { final GoRouter router = await createRouter( [], tester, - redirect: - (BuildContext context, GoRouterState state) => - state.matchedLocation == '/' - ? '/login?from=${state.uri}' - : state.matchedLocation == '/login' - ? '/' - : null, - errorBuilder: - (BuildContext context, GoRouterState state) => - TestErrorScreen(state.error!), + redirect: (BuildContext context, GoRouterState state) => + state.matchedLocation == '/' + ? '/login?from=${state.uri}' + : state.matchedLocation == '/login' + ? '/' + : null, + errorBuilder: (BuildContext context, GoRouterState state) => + TestErrorScreen(state.error!), ); final List matches = @@ -2842,8 +2770,8 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), ), GoRoute( path: '/dummy', @@ -2864,14 +2792,13 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), ), GoRoute( path: '/login', - builder: - (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => + const LoginScreen(), ), ]; @@ -2903,15 +2830,13 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => + const DummyScreen(), routes: [ GoRoute( path: ':id', - builder: - (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => + const DummyScreen(), ), ], ), @@ -2975,9 +2900,8 @@ void main() { routes: [ GoRoute( path: 'family/:fid', - builder: - (BuildContext c, GoRouterState s) => - FamilyScreen(s.pathParameters['fid']!), + builder: (BuildContext c, GoRouterState s) => + FamilyScreen(s.pathParameters['fid']!), routes: [ GoRoute( path: 'person/:pid', @@ -2986,11 +2910,10 @@ void main() { expect(s.pathParameters['pid'], 'p1'); return null; }, - builder: - (BuildContext c, GoRouterState s) => PersonScreen( - s.pathParameters['fid']!, - s.pathParameters['pid']!, - ), + builder: (BuildContext c, GoRouterState s) => PersonScreen( + s.pathParameters['fid']!, + s.pathParameters['pid']!, + ), ), ], ), @@ -3020,11 +2943,10 @@ void main() { final GoRouter router = await createRouter( [], tester, - redirect: - (BuildContext context, GoRouterState state) => '/${state.uri}+', - errorBuilder: - (BuildContext context, GoRouterState state) => - TestErrorScreen(state.error!), + redirect: (BuildContext context, GoRouterState state) => + '/${state.uri}+', + errorBuilder: (BuildContext context, GoRouterState state) => + TestErrorScreen(state.error!), redirectLimit: 10, ); @@ -3085,8 +3007,8 @@ void main() { GoRoute( name: 'home', path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), routes: [ GoRoute( name: 'login', @@ -3131,21 +3053,19 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), routes: [ GoRoute( path: 'dummy', - builder: - (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => + const DummyScreen(), redirect: (BuildContext context, GoRouterState state) => '/other', routes: [ GoRoute( path: 'dummy2', - builder: - (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => + const DummyScreen(), redirect: (BuildContext context, GoRouterState state) { assert(false); return '/other2'; @@ -3155,15 +3075,13 @@ void main() { ), GoRoute( path: 'other', - builder: - (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => + const DummyScreen(), ), GoRoute( path: 'other2', - builder: - (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => + const DummyScreen(), ), ], ), @@ -3187,29 +3105,25 @@ void main() { final List routes = [ ShellRoute( redirect: (BuildContext context, GoRouterState state) => '/dummy', - builder: - (BuildContext context, GoRouterState state, Widget child) => - Scaffold(appBar: AppBar(), body: child), + builder: (BuildContext context, GoRouterState state, Widget child) => + Scaffold(appBar: AppBar(), body: child), routes: [ GoRoute( path: '/other', - builder: - (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => + const DummyScreen(), ), GoRoute( path: '/other2', - builder: - (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => + const DummyScreen(), ), ], ), GoRoute( path: '/dummy', - builder: - (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => + const DummyScreen(), ), ]; @@ -3231,21 +3145,21 @@ void main() { final List routes = [ StatefulShellRoute.indexedStack( redirect: (BuildContext context, GoRouterState state) => '/dummy', - builder: ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - return navigationShell; - }, + builder: + ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + return navigationShell; + }, branches: [ StatefulShellBranch( routes: [ GoRoute( path: '/other', - builder: - (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => + const DummyScreen(), ), ], ), @@ -3253,9 +3167,8 @@ void main() { routes: [ GoRoute( path: '/other2', - builder: - (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => + const DummyScreen(), ), ], ), @@ -3263,9 +3176,8 @@ void main() { ), GoRoute( path: '/dummy', - builder: - (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => + const DummyScreen(), ), ]; @@ -3287,14 +3199,13 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), routes: [ GoRoute( path: 'dummy', - builder: - (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => + const DummyScreen(), ), ], ), @@ -3315,8 +3226,8 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), routes: [ GoRoute( path: 'dummy', @@ -3345,8 +3256,8 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), ), GoRoute( path: '/dummy', @@ -3367,22 +3278,21 @@ void main() { 'does not take precedence over platformDispatcher.defaultRouteName', (WidgetTester tester) async { TestWidgetsFlutterBinding - .instance - .platformDispatcher - .defaultRouteNameTestValue = '/dummy'; + .instance + .platformDispatcher + .defaultRouteNameTestValue = + '/dummy'; final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), routes: [ GoRoute( path: 'dummy', - builder: - (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => + const DummyScreen(), ), ], ), @@ -3413,8 +3323,8 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), ), ]; @@ -3423,9 +3333,10 @@ void main() { 'scheme, authority, no path', (WidgetTester tester) async { TestWidgetsFlutterBinding - .instance - .platformDispatcher - .defaultRouteNameTestValue = 'https://domain.com'; + .instance + .platformDispatcher + .defaultRouteNameTestValue = + 'https://domain.com'; final GoRouter router = await createRouter(routes, tester); expect(router.routeInformationProvider.value.uri.path, '/'); TestWidgetsFlutterBinding.instance.platformDispatcher @@ -3438,9 +3349,10 @@ void main() { 'scheme, authority, no path, but trailing slash', (WidgetTester tester) async { TestWidgetsFlutterBinding - .instance - .platformDispatcher - .defaultRouteNameTestValue = 'https://domain.com/'; + .instance + .platformDispatcher + .defaultRouteNameTestValue = + 'https://domain.com/'; final GoRouter router = await createRouter(routes, tester); expect(router.routeInformationProvider.value.uri.path, '/'); TestWidgetsFlutterBinding.instance.platformDispatcher @@ -3453,9 +3365,10 @@ void main() { 'scheme, authority, no path, and query parameters', (WidgetTester tester) async { TestWidgetsFlutterBinding - .instance - .platformDispatcher - .defaultRouteNameTestValue = 'https://domain.com?param=1'; + .instance + .platformDispatcher + .defaultRouteNameTestValue = + 'https://domain.com?param=1'; final GoRouter router = await createRouter(routes, tester); expect( router.routeInformationProvider.value.uri.toString(), @@ -3472,14 +3385,13 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), ), GoRoute( path: '/family/:fid', - builder: - (BuildContext context, GoRouterState state) => - FamilyScreen(state.pathParameters['fid']!), + builder: (BuildContext context, GoRouterState state) => + FamilyScreen(state.pathParameters['fid']!), ), ]; @@ -3502,14 +3414,13 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), ), GoRoute( path: '/family', - builder: - (BuildContext context, GoRouterState state) => - FamilyScreen(state.uri.queryParameters['fid']!), + builder: (BuildContext context, GoRouterState state) => + FamilyScreen(state.uri.queryParameters['fid']!), ), ]; @@ -3590,9 +3501,8 @@ void main() { routes: [ GoRoute(path: '/:id/:blah/:bam/:id/:blah', builder: dummy), ], - errorBuilder: - (BuildContext context, GoRouterState state) => - TestErrorScreen(state.error!), + errorBuilder: (BuildContext context, GoRouterState state) => + TestErrorScreen(state.error!), initialLocation: '/0/1/2/0/1', ); expect(false, true); @@ -3649,17 +3559,15 @@ void main() { GoRoute(path: '/', builder: dummy), GoRoute( path: '/family', - builder: - (BuildContext context, GoRouterState state) => - FamilyScreen(state.uri.queryParameters['fid']!), + builder: (BuildContext context, GoRouterState state) => + FamilyScreen(state.uri.queryParameters['fid']!), ), GoRoute( path: '/person', - builder: - (BuildContext context, GoRouterState state) => PersonScreen( - state.uri.queryParameters['fid']!, - state.uri.queryParameters['pid']!, - ), + builder: (BuildContext context, GoRouterState state) => PersonScreen( + state.uri.queryParameters['fid']!, + state.uri.queryParameters['pid']!, + ), ), ], tester); @@ -3684,17 +3592,15 @@ void main() { GoRoute(path: '/', builder: dummy), GoRoute( path: '/family', - builder: - (BuildContext context, GoRouterState state) => - FamilyScreen((state.extra! as Map)['fid']!), + builder: (BuildContext context, GoRouterState state) => + FamilyScreen((state.extra! as Map)['fid']!), ), GoRoute( path: '/person', - builder: - (BuildContext context, GoRouterState state) => PersonScreen( - (state.extra! as Map)['fid']!, - (state.extra! as Map)['pid']!, - ), + builder: (BuildContext context, GoRouterState state) => PersonScreen( + (state.extra! as Map)['fid']!, + (state.extra! as Map)['pid']!, + ), ), ], tester); @@ -3718,14 +3624,13 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), ), GoRoute( path: '/family/:fid', - builder: - (BuildContext context, GoRouterState state) => - FamilyScreen(state.pathParameters['fid']!), + builder: (BuildContext context, GoRouterState state) => + FamilyScreen(state.pathParameters['fid']!), routes: [ GoRoute( path: 'person/:pid', @@ -3764,22 +3669,22 @@ void main() { StatefulNavigationShell? routeState; final List routes = [ StatefulShellRoute.indexedStack( - builder: ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - routeState = navigationShell; - return navigationShell; - }, - branches: [ - StatefulShellBranch( + builder: + ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeState = navigationShell; + return navigationShell; + }, + branches: [ + StatefulShellBranch( routes: [ GoRoute( path: '/a', - builder: - (BuildContext context, GoRouterState state) => - const Text('Screen A'), + builder: (BuildContext context, GoRouterState state) => + const Text('Screen A'), ), ], ), @@ -3787,15 +3692,13 @@ void main() { routes: [ GoRoute( path: '/family', - builder: - (BuildContext context, GoRouterState state) => - const Text('Families'), + builder: (BuildContext context, GoRouterState state) => + const Text('Families'), routes: [ GoRoute( path: ':fid', - builder: - (BuildContext context, GoRouterState state) => - FamilyScreen(state.pathParameters['fid']!), + builder: (BuildContext context, GoRouterState state) => + FamilyScreen(state.pathParameters['fid']!), routes: [ GoRoute( path: 'person/:pid', @@ -3859,22 +3762,22 @@ void main() { Object? latestExtra; final List routes = [ StatefulShellRoute.indexedStack( - builder: ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - routeState = navigationShell; - return navigationShell; - }, + builder: + ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeState = navigationShell; + return navigationShell; + }, branches: [ StatefulShellBranch( routes: [ GoRoute( path: '/a', - builder: - (BuildContext context, GoRouterState state) => - const Text('Screen A'), + builder: (BuildContext context, GoRouterState state) => + const Text('Screen A'), ), ], ), @@ -3924,8 +3827,8 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), ), GoRoute( name: 'page', @@ -3984,8 +3887,8 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), ), GoRoute( name: 'page', @@ -4035,8 +3938,8 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), ), GoRoute( name: 'page', @@ -4077,15 +3980,14 @@ void main() { GoRoute( path: '/', name: 'home', - builder: - (BuildContext context, GoRouterState state) => - DummyStatefulWidget(key: key), + builder: (BuildContext context, GoRouterState state) => + DummyStatefulWidget(key: key), ), GoRoute( path: '/page1', name: 'page1', - builder: - (BuildContext context, GoRouterState state) => const Page1Screen(), + builder: (BuildContext context, GoRouterState state) => + const Page1Screen(), ), ]; @@ -4447,9 +4349,8 @@ void main() { routes: [ GoRoute( path: '/a', - builder: - (BuildContext context, GoRouterState state) => - const Text('Screen A'), + builder: (BuildContext context, GoRouterState state) => + const Text('Screen A'), ), ], ), @@ -4457,9 +4358,8 @@ void main() { routes: [ GoRoute( path: '/b', - builder: - (BuildContext context, GoRouterState state) => - const Text('Screen B'), + builder: (BuildContext context, GoRouterState state) => + const Text('Screen B'), ), ], ), @@ -4491,8 +4391,8 @@ void main() { final List routes = [ GoRoute( path: '/root', - builder: - (BuildContext context, GoRouterState state) => const Text('Root'), + builder: (BuildContext context, GoRouterState state) => + const Text('Root'), routes: [ StatefulShellRoute.indexedStack( builder: @@ -4506,9 +4406,8 @@ void main() { routes: [ GoRoute( path: 'a', - builder: - (BuildContext context, GoRouterState state) => - const Text('Screen A'), + builder: (BuildContext context, GoRouterState state) => + const Text('Screen A'), ), ], ), @@ -4516,9 +4415,8 @@ void main() { routes: [ GoRoute( path: 'b', - builder: - (BuildContext context, GoRouterState state) => - const Text('Screen B'), + builder: (BuildContext context, GoRouterState state) => + const Text('Screen B'), ), ], ), @@ -4554,22 +4452,22 @@ void main() { final List routes = [ StatefulShellRoute.indexedStack( - builder: ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - routeState = navigationShell; - return navigationShell; - }, + builder: + ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeState = navigationShell; + return navigationShell; + }, branches: [ StatefulShellBranch( routes: [ GoRoute( path: '/a', - builder: - (BuildContext context, GoRouterState state) => - const Text('Screen A'), + builder: (BuildContext context, GoRouterState state) => + const Text('Screen A'), ), ], ), @@ -4577,9 +4475,8 @@ void main() { routes: [ GoRoute( path: '/b', - builder: - (BuildContext context, GoRouterState state) => - const Text('Screen B'), + builder: (BuildContext context, GoRouterState state) => + const Text('Screen B'), ), ], ), @@ -4587,9 +4484,8 @@ void main() { routes: [ GoRoute( path: '/c', - builder: - (BuildContext context, GoRouterState state) => - const Text('Screen C'), + builder: (BuildContext context, GoRouterState state) => + const Text('Screen C'), ), ], ), @@ -4597,9 +4493,8 @@ void main() { routes: [ GoRoute( path: '/d', - builder: - (BuildContext context, GoRouterState state) => - const Text('Screen D'), + builder: (BuildContext context, GoRouterState state) => + const Text('Screen D'), ), ], ), @@ -4659,33 +4554,32 @@ void main() { final List routes = [ StatefulShellRoute.indexedStack( - builder: ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - routeState = navigationShell; - return navigationShell; - }, + builder: + ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeState = navigationShell; + return navigationShell; + }, branches: [ StatefulShellBranch( routes: [ GoRoute( path: '/a', - builder: - (BuildContext context, GoRouterState state) => - const Text('Screen A'), + builder: (BuildContext context, GoRouterState state) => + const Text('Screen A'), routes: [ GoRoute( path: 'detailA', - builder: - (BuildContext context, GoRouterState state) => - Column( - children: [ - const Text('Screen A Detail'), - DummyStatefulWidget(key: statefulWidgetKey), - ], - ), + builder: (BuildContext context, GoRouterState state) => + Column( + children: [ + const Text('Screen A Detail'), + DummyStatefulWidget(key: statefulWidgetKey), + ], + ), ), ], ), @@ -4695,9 +4589,8 @@ void main() { routes: [ GoRoute( path: '/b', - builder: - (BuildContext context, GoRouterState state) => - const Text('Screen B'), + builder: (BuildContext context, GoRouterState state) => + const Text('Screen B'), ), ], ), @@ -4748,22 +4641,22 @@ void main() { builder: (_, __) => const Placeholder(), routes: [ StatefulShellRoute.indexedStack( - builder: ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - routeState = navigationShell; - return navigationShell; - }, + builder: + ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeState = navigationShell; + return navigationShell; + }, branches: [ StatefulShellBranch( routes: [ GoRoute( path: 'a', - builder: - (BuildContext context, GoRouterState state) => - Text('a id is ${state.pathParameters['id']}'), + builder: (BuildContext context, GoRouterState state) => + Text('a id is ${state.pathParameters['id']}'), ), ], ), @@ -4771,9 +4664,8 @@ void main() { routes: [ GoRoute( path: 'b', - builder: - (BuildContext context, GoRouterState state) => - Text('b id is ${state.pathParameters['id']}'), + builder: (BuildContext context, GoRouterState state) => + Text('b id is ${state.pathParameters['id']}'), ), ], ), @@ -4804,26 +4696,28 @@ void main() { final List routes = [ StatefulShellRoute.indexedStack( - builder: ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - routeState1 = navigationShell; - return navigationShell; - }, + builder: + ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeState1 = navigationShell; + return navigationShell; + }, branches: [ StatefulShellBranch( routes: [ StatefulShellRoute.indexedStack( - builder: ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - routeState2 = navigationShell; - return navigationShell; - }, + builder: + ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeState2 = navigationShell; + return navigationShell; + }, branches: [ StatefulShellBranch( routes: [ @@ -4878,9 +4772,8 @@ void main() { routes: [ GoRoute( path: '/d', - builder: - (BuildContext context, GoRouterState state) => - const Text('Screen D'), + builder: (BuildContext context, GoRouterState state) => + const Text('Screen D'), ), ], ), @@ -4932,29 +4825,28 @@ void main() { final List routes = [ StatefulShellRoute.indexedStack( - builder: ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - routeState = navigationShell; - return navigationShell; - }, + builder: + ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeState = navigationShell; + return navigationShell; + }, branches: [ StatefulShellBranch( navigatorKey: sectionANavigatorKey, routes: [ GoRoute( path: '/a', - builder: - (BuildContext context, GoRouterState state) => - const Text('Screen A'), + builder: (BuildContext context, GoRouterState state) => + const Text('Screen A'), routes: [ GoRoute( path: 'detailA', - builder: - (BuildContext context, GoRouterState state) => - const Text('Screen A Detail'), + builder: (BuildContext context, GoRouterState state) => + const Text('Screen A Detail'), ), ], ), @@ -4965,15 +4857,13 @@ void main() { routes: [ GoRoute( path: '/b', - builder: - (BuildContext context, GoRouterState state) => - const Text('Screen B'), + builder: (BuildContext context, GoRouterState state) => + const Text('Screen B'), routes: [ GoRoute( path: 'detailB', - builder: - (BuildContext context, GoRouterState state) => - const Text('Screen B Detail'), + builder: (BuildContext context, GoRouterState state) => + const Text('Screen B Detail'), ), ], ), @@ -5030,22 +4920,22 @@ void main() { final List routes = [ StatefulShellRoute.indexedStack( - builder: ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - routeState = navigationShell; - return navigationShell; - }, + builder: + ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeState = navigationShell; + return navigationShell; + }, branches: [ StatefulShellBranch( routes: [ GoRoute( path: '/a', - builder: - (BuildContext context, GoRouterState state) => - const Text('Screen A'), + builder: (BuildContext context, GoRouterState state) => + const Text('Screen A'), ), ], ), @@ -5053,9 +4943,8 @@ void main() { routes: [ GoRoute( path: '/b', - builder: - (BuildContext context, GoRouterState state) => - Text('Screen B - ${state.extra}'), + builder: (BuildContext context, GoRouterState state) => + Text('Screen B - ${state.extra}'), ), ], ), @@ -5098,27 +4987,26 @@ void main() { final List routes = [ GoRoute( path: '/common', - builder: - (BuildContext context, GoRouterState state) => - Text('Common - ${state.extra}'), + builder: (BuildContext context, GoRouterState state) => + Text('Common - ${state.extra}'), ), StatefulShellRoute.indexedStack( - builder: ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - routeState = navigationShell; - return navigationShell; - }, + builder: + ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeState = navigationShell; + return navigationShell; + }, branches: [ StatefulShellBranch( routes: [ GoRoute( path: '/a', - builder: - (BuildContext context, GoRouterState state) => - const Text('Screen A'), + builder: (BuildContext context, GoRouterState state) => + const Text('Screen A'), ), ], ), @@ -5126,9 +5014,8 @@ void main() { routes: [ GoRoute( path: '/b', - builder: - (BuildContext context, GoRouterState state) => - const Text('Screen B'), + builder: (BuildContext context, GoRouterState state) => + const Text('Screen B'), ), ], ), @@ -5190,9 +5077,8 @@ void main() { routes: [ GoRoute( path: '/a', - builder: - (BuildContext context, GoRouterState state) => - DummyStatefulWidget(key: statefulWidgetKeyA), + builder: (BuildContext context, GoRouterState state) => + DummyStatefulWidget(key: statefulWidgetKeyA), ), ], ), @@ -5200,9 +5086,8 @@ void main() { routes: [ GoRoute( path: '/b', - builder: - (BuildContext context, GoRouterState state) => - DummyStatefulWidget(key: statefulWidgetKeyB), + builder: (BuildContext context, GoRouterState state) => + DummyStatefulWidget(key: statefulWidgetKeyB), ), ], ), @@ -5216,9 +5101,8 @@ void main() { routes: [ GoRoute( path: '/c', - builder: - (BuildContext context, GoRouterState state) => - DummyStatefulWidget(key: statefulWidgetKeyC), + builder: (BuildContext context, GoRouterState state) => + DummyStatefulWidget(key: statefulWidgetKeyC), ), ], ), @@ -5227,9 +5111,8 @@ void main() { routes: [ GoRoute( path: '/d', - builder: - (BuildContext context, GoRouterState state) => - DummyStatefulWidget(key: statefulWidgetKeyD), + builder: (BuildContext context, GoRouterState state) => + DummyStatefulWidget(key: statefulWidgetKeyD), ), ], ), @@ -5239,15 +5122,13 @@ void main() { routes: [ GoRoute( path: '/e', - builder: - (BuildContext context, GoRouterState state) => - const Text('E'), + builder: (BuildContext context, GoRouterState state) => + const Text('E'), routes: [ GoRoute( path: 'details', - builder: - (BuildContext context, GoRouterState state) => - DummyStatefulWidget(key: statefulWidgetKeyE), + builder: (BuildContext context, GoRouterState state) => + DummyStatefulWidget(key: statefulWidgetKeyE), ), ], ), @@ -5330,9 +5211,8 @@ void main() { routes: [ GoRoute( path: '/c', - builder: - (BuildContext context, GoRouterState state) => - DummyStatefulWidget(key: statefulWidgetKeyC), + builder: (BuildContext context, GoRouterState state) => + DummyStatefulWidget(key: statefulWidgetKeyC), ), ], ), @@ -5340,9 +5220,8 @@ void main() { routes: [ GoRoute( path: '/d', - builder: - (BuildContext context, GoRouterState state) => - DummyStatefulWidget(key: statefulWidgetKeyD), + builder: (BuildContext context, GoRouterState state) => + DummyStatefulWidget(key: statefulWidgetKeyD), ), ], ), @@ -5370,22 +5249,22 @@ void main() { final List routes = [ StatefulShellRoute.indexedStack( - builder: ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - routeState = navigationShell; - return navigationShell; - }, + builder: + ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeState = navigationShell; + return navigationShell; + }, branches: [ StatefulShellBranch( routes: [ GoRoute( path: '/a', - builder: - (BuildContext context, GoRouterState state) => - const Text('Screen A'), + builder: (BuildContext context, GoRouterState state) => + const Text('Screen A'), ), ], ), @@ -5393,21 +5272,18 @@ void main() { routes: [ GoRoute( path: '/b', - builder: - (BuildContext context, GoRouterState state) => - const Text('Screen B'), + builder: (BuildContext context, GoRouterState state) => + const Text('Screen B'), routes: [ GoRoute( path: 'details1', - builder: - (BuildContext context, GoRouterState state) => - const Text('Screen B Detail1'), + builder: (BuildContext context, GoRouterState state) => + const Text('Screen B Detail1'), ), GoRoute( path: 'details2', - builder: - (BuildContext context, GoRouterState state) => - const Text('Screen B Detail2'), + builder: (BuildContext context, GoRouterState state) => + const Text('Screen B Detail2'), ), ], ), @@ -5418,15 +5294,13 @@ void main() { GoRoute(path: '/c', redirect: (_, __) => '/c/main2'), GoRoute( path: '/c/main1', - builder: - (BuildContext context, GoRouterState state) => - const Text('Screen C1'), + builder: (BuildContext context, GoRouterState state) => + const Text('Screen C1'), ), GoRoute( path: '/c/main2', - builder: - (BuildContext context, GoRouterState state) => - const Text('Screen C2'), + builder: (BuildContext context, GoRouterState state) => + const Text('Screen C2'), ), ], ), @@ -5481,22 +5355,22 @@ void main() { final List routes = [ // First level shell StatefulShellRoute.indexedStack( - builder: ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - routeState = navigationShell; - return navigationShell; - }, + builder: + ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeState = navigationShell; + return navigationShell; + }, branches: [ StatefulShellBranch( routes: [ GoRoute( path: '/a', - builder: - (BuildContext context, GoRouterState state) => - const Text('Screen A'), + builder: (BuildContext context, GoRouterState state) => + const Text('Screen A'), ), ], ), @@ -5552,9 +5426,8 @@ void main() { GoRoute( path: '/top-modal', parentNavigatorKey: rootNavigatorKey, - builder: - (BuildContext context, GoRouterState state) => - const Text('Top Modal'), + builder: (BuildContext context, GoRouterState state) => + const Text('Top Modal'), ), ]; @@ -5620,9 +5493,8 @@ void main() { routes: [ GoRoute( path: '/$name', - builder: - (BuildContext context, GoRouterState state) => - Text('Screen $name'), + builder: (BuildContext context, GoRouterState state) => + Text('Screen $name'), ), ], ); @@ -5630,14 +5502,15 @@ void main() { List createRoutes(bool includeCRoute) => [ StatefulShellRoute.indexedStack( key: statefulShellKey, - builder: ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - routeState = navigationShell; - return navigationShell; - }, + builder: + ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeState = navigationShell; + return navigationShell; + }, branches: [ makeBranch('a'), makeBranch('b'), @@ -5746,16 +5619,13 @@ void main() { routes: [ ShellRoute( navigatorKey: shellNavigatorKey, - builder: ( - BuildContext context, - GoRouterState state, - Widget child, - ) { - return Scaffold( - appBar: AppBar(title: const Text('Shell')), - body: child, - ); - }, + builder: + (BuildContext context, GoRouterState state, Widget child) { + return Scaffold( + appBar: AppBar(title: const Text('Shell')), + body: child, + ); + }, routes: [ GoRoute( path: '/a', @@ -5891,22 +5761,19 @@ void main() { routes: [ ShellRoute( navigatorKey: shell, - builder: ( - BuildContext context, - GoRouterState state, - Widget child, - ) { - return Scaffold( - body: Center( - child: Column( - children: [ - const Text('Shell'), - Expanded(child: child), - ], - ), - ), - ); - }, + builder: + (BuildContext context, GoRouterState state, Widget child) { + return Scaffold( + body: Center( + child: Column( + children: [ + const Text('Shell'), + Expanded(child: child), + ], + ), + ), + ); + }, routes: [ GoRoute(path: '/', builder: (_, __) => const Text('A Screen')), ], @@ -5953,22 +5820,23 @@ void main() { routes: [ ShellRoute( navigatorKey: shell, - builder: ( - BuildContext context, - GoRouterState state, - Widget child, - ) { - return Scaffold( - body: Center( - child: Column( - children: [ - const Text('Shell'), - Expanded(child: child), - ], - ), - ), - ); - }, + builder: + ( + BuildContext context, + GoRouterState state, + Widget child, + ) { + return Scaffold( + body: Center( + child: Column( + children: [ + const Text('Shell'), + Expanded(child: child), + ], + ), + ), + ); + }, routes: [ GoRoute( path: 'a', @@ -6036,22 +5904,23 @@ void main() { routes: [ ShellRoute( navigatorKey: shell, - builder: ( - BuildContext context, - GoRouterState state, - Widget child, - ) { - return Scaffold( - body: Center( - child: Column( - children: [ - const Text('Shell'), - Expanded(child: child), - ], - ), - ), - ); - }, + builder: + ( + BuildContext context, + GoRouterState state, + Widget child, + ) { + return Scaffold( + body: Center( + child: Column( + children: [ + const Text('Shell'), + Expanded(child: child), + ], + ), + ), + ); + }, routes: [ GoRoute( path: 'a', @@ -6149,7 +6018,10 @@ void main() { ) async { const Key key = Key('key'); final List routes = [ - GoRoute(path: '/', builder: (_, __) => const SizedBox(key: key)), + GoRoute( + path: '/', + builder: (_, __) => const SizedBox(key: key), + ), ]; final GoRouter router = await createRouter(routes, tester); @@ -6175,7 +6047,10 @@ void main() { ) async { const Key key = Key('key'); final List routes = [ - GoRoute(path: '/', builder: (_, __) => const SizedBox(key: key)), + GoRoute( + path: '/', + builder: (_, __) => const SizedBox(key: key), + ), ]; final GoRouter router = await createRouter(routes, tester); @@ -6262,17 +6137,18 @@ void main() { final List routes = [ StatefulShellRoute.indexedStack( restorationScopeId: 'shell', - pageBuilder: ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - routeState = navigationShell; - return MaterialPage( - restorationId: 'shellWidget', - child: navigationShell, - ); - }, + pageBuilder: + ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeState = navigationShell; + return MaterialPage( + restorationId: 'shellWidget', + child: navigationShell, + ); + }, branches: [ StatefulShellBranch( restorationScopeId: 'branchA', @@ -6422,17 +6298,18 @@ void main() { final List routes = [ StatefulShellRoute.indexedStack( restorationScopeId: 'shell', - pageBuilder: ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - routeStateRoot = navigationShell; - return MaterialPage( - restorationId: 'shellWidget', - child: navigationShell, - ); - }, + pageBuilder: + ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeStateRoot = navigationShell; + return MaterialPage( + restorationId: 'shellWidget', + child: navigationShell, + ); + }, branches: [ StatefulShellBranch( restorationScopeId: 'branchA', @@ -6468,17 +6345,18 @@ void main() { routes: [ StatefulShellRoute.indexedStack( restorationScopeId: 'branchB-nested-shell', - pageBuilder: ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - routeStateNested = navigationShell; - return MaterialPage( - restorationId: 'shellWidget-nested', - child: navigationShell, - ); - }, + pageBuilder: + ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeStateNested = navigationShell; + return MaterialPage( + restorationId: 'shellWidget-nested', + child: navigationShell, + ); + }, branches: [ StatefulShellBranch( restorationScopeId: 'branchB-nested', @@ -6589,15 +6467,13 @@ void main() { routes: [ GoRoute( path: '/a', - builder: - (BuildContext context, GoRouterState state) => - const Placeholder(), + builder: (BuildContext context, GoRouterState state) => + const Placeholder(), ), GoRoute( path: '/b', - builder: - (BuildContext context, GoRouterState state) => - const Placeholder(), + builder: (BuildContext context, GoRouterState state) => + const Placeholder(), ), ], ), @@ -6617,15 +6493,13 @@ void main() { final List routes = [ GoRoute( path: '/abc', - builder: - (BuildContext context, GoRouterState state) => - const Placeholder(), + builder: (BuildContext context, GoRouterState state) => + const Placeholder(), ), GoRoute( path: '/bcd', - builder: - (BuildContext context, GoRouterState state) => - const Placeholder(), + builder: (BuildContext context, GoRouterState state) => + const Placeholder(), ), ]; @@ -6683,34 +6557,30 @@ void main() { GoRoute( name: 'home', path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), ), GoRoute( name: 'books', path: '/books', - builder: - (BuildContext context, GoRouterState state) => - const Text('books'), + builder: (BuildContext context, GoRouterState state) => + const Text('books'), ), GoRoute( name: 'boats', path: '/boats', - builder: - (BuildContext context, GoRouterState state) => - const Text('boats'), + builder: (BuildContext context, GoRouterState state) => + const Text('boats'), ), ShellRoute( - builder: - (BuildContext context, GoRouterState state, Widget child) => - child, + builder: (BuildContext context, GoRouterState state, Widget child) => + child, routes: [ GoRoute( name: 'tulips', path: '/tulips', - builder: - (BuildContext context, GoRouterState state) => - const Text('tulips'), + builder: (BuildContext context, GoRouterState state) => + const Text('tulips'), ), ], ), @@ -6762,26 +6632,23 @@ void main() { final List routes = [ GoRoute( path: '/', // root cannot be empty (existing assert) - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), routes: [ GoRoute( path: 'child-route', - builder: - (BuildContext context, GoRouterState state) => - const Text('/child-route'), + builder: (BuildContext context, GoRouterState state) => + const Text('/child-route'), routes: [ GoRoute( path: 'grand-child-route', - builder: - (BuildContext context, GoRouterState state) => - const Text('/grand-child-route'), + builder: (BuildContext context, GoRouterState state) => + const Text('/grand-child-route'), ), GoRoute( path: 'redirected-grand-child-route', - redirect: - (BuildContext context, GoRouterState state) => - '/child-route', + redirect: (BuildContext context, GoRouterState state) => + '/child-route', ), ], ), @@ -6813,26 +6680,23 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => + const HomeScreen(), routes: [ GoRoute( path: '/child-route', - builder: - (BuildContext context, GoRouterState state) => - const Text('/child-route'), + builder: (BuildContext context, GoRouterState state) => + const Text('/child-route'), routes: [ GoRoute( path: '/grand-child-route', - builder: - (BuildContext context, GoRouterState state) => - const Text('/grand-child-route'), + builder: (BuildContext context, GoRouterState state) => + const Text('/grand-child-route'), ), GoRoute( path: '/redirected-grand-child-route', - redirect: - (BuildContext context, GoRouterState state) => - '/child-route', + redirect: (BuildContext context, GoRouterState state) => + '/child-route', ), ], ), diff --git a/packages/go_router/test/imperative_api_test.dart b/packages/go_router/test/imperative_api_test.dart index 4075e3374b0..de3cbda0cf0 100644 --- a/packages/go_router/test/imperative_api_test.dart +++ b/packages/go_router/test/imperative_api_test.dart @@ -22,8 +22,14 @@ void main() { ); }, routes: [ - GoRoute(path: '/a', builder: (_, __) => DummyScreen(key: a)), - GoRoute(path: '/b', builder: (_, __) => DummyScreen(key: b)), + GoRoute( + path: '/a', + builder: (_, __) => DummyScreen(key: a), + ), + GoRoute( + path: '/b', + builder: (_, __) => DummyScreen(key: b), + ), ], ), ]; @@ -48,7 +54,10 @@ void main() { final UniqueKey a = UniqueKey(); final UniqueKey b = UniqueKey(); final List routes = [ - GoRoute(path: '/a', builder: (_, __) => DummyScreen(key: a)), + GoRoute( + path: '/a', + builder: (_, __) => DummyScreen(key: a), + ), ShellRoute( builder: (_, __, Widget child) { return Scaffold( @@ -57,7 +66,10 @@ void main() { ); }, routes: [ - GoRoute(path: '/b', builder: (_, __) => DummyScreen(key: b)), + GoRoute( + path: '/b', + builder: (_, __) => DummyScreen(key: b), + ), ], ), ]; @@ -96,7 +108,10 @@ void main() { path: '/', builder: (_, __) => DummyScreen(key: home), routes: [ - GoRoute(path: 'a', builder: (_, __) => DummyScreen(key: a)), + GoRoute( + path: 'a', + builder: (_, __) => DummyScreen(key: a), + ), ], ), ], @@ -139,7 +154,10 @@ void main() { ); }, routes: [ - GoRoute(path: '/a', builder: (_, __) => DummyScreen(key: a)), + GoRoute( + path: '/a', + builder: (_, __) => DummyScreen(key: a), + ), ], ), ShellRoute( @@ -150,7 +168,10 @@ void main() { ); }, routes: [ - GoRoute(path: '/b', builder: (_, __) => DummyScreen(key: b)), + GoRoute( + path: '/b', + builder: (_, __) => DummyScreen(key: b), + ), ], ), ]; @@ -186,10 +207,16 @@ void main() { ); }, routes: [ - GoRoute(path: '/in', builder: (_, __) => DummyScreen(key: inside)), + GoRoute( + path: '/in', + builder: (_, __) => DummyScreen(key: inside), + ), ], ), - GoRoute(path: '/out', builder: (_, __) => DummyScreen(key: outside)), + GoRoute( + path: '/out', + builder: (_, __) => DummyScreen(key: outside), + ), ]; final GoRouter router = await createRouter( routes, @@ -229,18 +256,30 @@ void main() { ); }, routes: [ - GoRoute(path: '/a', builder: (_, __) => DummyScreen(key: a)), - GoRoute(path: '/c', builder: (_, __) => DummyScreen(key: c)), + GoRoute( + path: '/a', + builder: (_, __) => DummyScreen(key: a), + ), + GoRoute( + path: '/c', + builder: (_, __) => DummyScreen(key: c), + ), ], ), GoRoute( path: '/d', builder: (_, __) => DummyScreen(key: d), routes: [ - GoRoute(path: 'e', builder: (_, __) => DummyScreen(key: e)), + GoRoute( + path: 'e', + builder: (_, __) => DummyScreen(key: e), + ), ], ), - GoRoute(path: '/b', builder: (_, __) => DummyScreen(key: b)), + GoRoute( + path: '/b', + builder: (_, __) => DummyScreen(key: b), + ), ]; final GoRouter router = await createRouter( routes, diff --git a/packages/go_router/test/matching_test.dart b/packages/go_router/test/matching_test.dart index 48cdf5db48c..e195d182d85 100644 --- a/packages/go_router/test/matching_test.dart +++ b/packages/go_router/test/matching_test.dart @@ -18,8 +18,8 @@ void main() { final List routes = [ GoRoute( path: '/page-0', - builder: - (BuildContext context, GoRouterState state) => const Placeholder(), + builder: (BuildContext context, GoRouterState state) => + const Placeholder(), ), ]; @@ -36,8 +36,8 @@ void main() { test('RouteMatchList compares', () async { final GoRoute route = GoRoute( path: '/page-0', - builder: - (BuildContext context, GoRouterState state) => const Placeholder(), + builder: (BuildContext context, GoRouterState state) => + const Placeholder(), ); final Map params1 = {}; final List match1 = RouteMatchBase.match( @@ -82,15 +82,13 @@ void main() { routes: [ GoRoute( path: '/a', - builder: - (BuildContext context, GoRouterState state) => - const Placeholder(), + builder: (BuildContext context, GoRouterState state) => + const Placeholder(), ), GoRoute( path: '/b', - builder: - (BuildContext context, GoRouterState state) => - const Placeholder(), + builder: (BuildContext context, GoRouterState state) => + const Placeholder(), ), ], redirectLimit: 0, diff --git a/packages/go_router/test/on_enter_test.dart b/packages/go_router/test/on_enter_test.dart index 58f43d3a690..310780e9715 100644 --- a/packages/go_router/test/on_enter_test.dart +++ b/packages/go_router/test/on_enter_test.dart @@ -27,17 +27,18 @@ void main() { router = GoRouter( initialLocation: '/', - onEnter: ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - ) async { - onEnterCallCount++; - capturedCurrentState = current; - capturedNextState = next; - return const Allow(); - }, + onEnter: + ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + ) async { + onEnterCallCount++; + capturedCurrentState = current; + capturedNextState = next; + return const Allow(); + }, routes: [ GoRoute( path: '/', @@ -65,18 +66,19 @@ void main() { router = GoRouter( initialLocation: '/', - onEnter: ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - ) async { - navigationAttempts.add(next.uri.path); - currentPath = current.uri.path; - return next.uri.path.contains('blocked') - ? const Block.stop() - : const Allow(); - }, + onEnter: + ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + ) async { + navigationAttempts.add(next.uri.path); + currentPath = current.uri.path; + return next.uri.path.contains('blocked') + ? const Block.stop() + : const Allow(); + }, routes: [ GoRoute( path: '/', @@ -136,34 +138,33 @@ void main() { router = GoRouter( initialLocation: '/home', - onEnter: ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - ) async { - onEnterCallCount++; - return next.uri.path.contains('block') - ? const Block.stop() - : const Allow(); - }, + onEnter: + ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + ) async { + onEnterCallCount++; + return next.uri.path.contains('block') + ? const Block.stop() + : const Allow(); + }, routes: [ GoRoute( path: '/home', - builder: - (_, __) => const Scaffold(body: Center(child: Text('Home'))), + builder: (_, __) => + const Scaffold(body: Center(child: Text('Home'))), routes: [ GoRoute( path: 'allowed', - builder: - (_, __) => - const Scaffold(body: Center(child: Text('Allowed'))), + builder: (_, __) => + const Scaffold(body: Center(child: Text('Allowed'))), ), GoRoute( path: 'block', - builder: - (_, __) => - const Scaffold(body: Center(child: Text('Blocked'))), + builder: (_, __) => + const Scaffold(body: Center(child: Text('Blocked'))), ), ], ), @@ -197,43 +198,39 @@ void main() { router = GoRouter( initialLocation: '/start', redirectLimit: 2, - onException: ( - BuildContext context, - GoRouterState state, - GoRouter goRouter, - ) { - capturedError = state.error; - goRouter.go('/fallback'); - completer.complete(); - }, - onEnter: ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - ) async { - if (next.uri.path == '/recursive') { - return Block.then(() => goRouter.push('/recursive')); - } - return const Allow(); - }, + onException: + (BuildContext context, GoRouterState state, GoRouter goRouter) { + capturedError = state.error; + goRouter.go('/fallback'); + completer.complete(); + }, + onEnter: + ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + ) async { + if (next.uri.path == '/recursive') { + return Block.then(() => goRouter.push('/recursive')); + } + return const Allow(); + }, routes: [ GoRoute( path: '/start', - builder: - (_, __) => const Scaffold(body: Center(child: Text('Start'))), + builder: (_, __) => + const Scaffold(body: Center(child: Text('Start'))), ), GoRoute( path: '/recursive', - builder: - (_, __) => - const Scaffold(body: Center(child: Text('Recursive'))), + builder: (_, __) => + const Scaffold(body: Center(child: Text('Recursive'))), ), GoRoute( path: '/fallback', - builder: - (_, __) => - const Scaffold(body: Center(child: Text('Fallback'))), + builder: (_, __) => + const Scaffold(body: Center(child: Text('Fallback'))), ), ], ); @@ -264,47 +261,50 @@ void main() { final StreamController<({String current, String next})> paramsSink = StreamController<({String current, String next})>(); - final Stream<({String current, String next})> paramsStream = - paramsSink.stream.asBroadcastStream(); + final Stream<({String current, String next})> paramsStream = paramsSink + .stream + .asBroadcastStream(); router = GoRouter( initialLocation: '/home', - onEnter: ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - ) async { - final bool isProtected = next.uri.toString().contains('protected'); - paramsSink.add(( - current: current.uri.toString(), - next: next.uri.toString(), - )); - - if (!isProtected) { - return const Allow(); - } - if (await isAuthenticated()) { - return const Allow(); - } - return Block.then(() => router.go('/sign-in')); - }, + onEnter: + ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + ) async { + final bool isProtected = next.uri.toString().contains( + 'protected', + ); + paramsSink.add(( + current: current.uri.toString(), + next: next.uri.toString(), + )); + + if (!isProtected) { + return const Allow(); + } + if (await isAuthenticated()) { + return const Allow(); + } + return Block.then(() => router.go('/sign-in')); + }, routes: [ GoRoute( path: '/home', - builder: - (_, __) => const Scaffold(body: Center(child: Text('Home'))), + builder: (_, __) => + const Scaffold(body: Center(child: Text('Home'))), ), GoRoute( path: '/protected', - builder: - (_, __) => - const Scaffold(body: Center(child: Text('Protected'))), + builder: (_, __) => + const Scaffold(body: Center(child: Text('Protected'))), ), GoRoute( path: '/sign-in', - builder: - (_, __) => const Scaffold(body: Center(child: Text('Sign-in'))), + builder: (_, __) => + const Scaffold(body: Center(child: Text('Sign-in'))), ), ], ); @@ -341,57 +341,58 @@ void main() { router = GoRouter( initialLocation: '/home', - onEnter: ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - ) async { - navigationAttempts.add(next.uri.path); - - if (next.uri.path == '/requires-auth') { - return Block.then( - () => goRouter.goNamed( - 'login-page', - queryParameters: {'from': next.uri.toString()}, - ), - ); - } - return const Allow(); - }, + onEnter: + ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + ) async { + navigationAttempts.add(next.uri.path); + + if (next.uri.path == '/requires-auth') { + return Block.then( + () => goRouter.goNamed( + 'login-page', + queryParameters: { + 'from': next.uri.toString(), + }, + ), + ); + } + return const Allow(); + }, routes: [ GoRoute( path: '/home', - builder: - (_, __) => const Scaffold(body: Center(child: Text('Home'))), + builder: (_, __) => + const Scaffold(body: Center(child: Text('Home'))), ), GoRoute( path: '/requires-auth', - builder: - (_, __) => const Scaffold( - body: Center(child: Text('Authenticated Content')), - ), + builder: (_, __) => const Scaffold( + body: Center(child: Text('Authenticated Content')), + ), ), GoRoute( path: '/login', name: 'login-page', - builder: - (_, GoRouterState state) => Scaffold( - body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Text( - 'Login Page - From: ${state.uri.queryParameters['from'] ?? 'unknown'}', - ), - ElevatedButton( - onPressed: () => router.go('/home'), - child: const Text('Go Home'), - ), - ], + builder: (_, GoRouterState state) => Scaffold( + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + 'Login Page - From: ${state.uri.queryParameters['from'] ?? 'unknown'}', ), - ), + ElevatedButton( + onPressed: () => router.go('/home'), + child: const Text('Go Home'), + ), + ], ), + ), + ), ), ], ); @@ -417,55 +418,57 @@ void main() { final StreamController<({String current, String next})> paramsSink = StreamController<({String current, String next})>(); - final Stream<({String current, String next})> paramsStream = - paramsSink.stream.asBroadcastStream(); + final Stream<({String current, String next})> paramsStream = paramsSink + .stream + .asBroadcastStream(); router = GoRouter( initialLocation: '/home', - onEnter: ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - ) async { - final bool isProtected = next.uri.toString().contains('protected'); - paramsSink.add(( - current: current.uri.toString(), - next: next.uri.toString(), - )); - if (!isProtected) { - return const Allow(); - } - if (await isAuthenticated()) { - return const Allow(); - } - await router.push('/sign-in').then((bool? isLoggedIn) { - if (isLoggedIn ?? false) { - router.go(next.uri.toString()); - } - }); - - return const Block.stop(); - }, + onEnter: + ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + ) async { + final bool isProtected = next.uri.toString().contains( + 'protected', + ); + paramsSink.add(( + current: current.uri.toString(), + next: next.uri.toString(), + )); + if (!isProtected) { + return const Allow(); + } + if (await isAuthenticated()) { + return const Allow(); + } + await router.push('/sign-in').then((bool? isLoggedIn) { + if (isLoggedIn ?? false) { + router.go(next.uri.toString()); + } + }); + + return const Block.stop(); + }, routes: [ GoRoute( path: '/home', - builder: - (_, __) => const Scaffold(body: Center(child: Text('Home'))), + builder: (_, __) => + const Scaffold(body: Center(child: Text('Home'))), ), GoRoute( path: '/protected', - builder: - (_, __) => - const Scaffold(body: Center(child: Text('Protected'))), + builder: (_, __) => + const Scaffold(body: Center(child: Text('Protected'))), ), GoRoute( path: '/sign-in', - builder: - (_, __) => Scaffold( - appBar: AppBar(title: const Text('Sign in')), - body: const Center(child: Text('Sign-in')), - ), + builder: (_, __) => Scaffold( + appBar: AppBar(title: const Text('Sign in')), + body: const Center(child: Text('Sign-in')), + ), ), ], ); @@ -501,38 +504,37 @@ void main() { router = GoRouter( initialLocation: '/home', - onEnter: ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - ) async { - navigationHistory.add('Entering: ${next.uri.path}'); - - if (next.uri.path == '/old-page') { - navigationHistory.add('Replacing with /new-version'); - await goRouter.replace('/new-version'); - return const Block.stop(); - } - return const Allow(); - }, + onEnter: + ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + ) async { + navigationHistory.add('Entering: ${next.uri.path}'); + + if (next.uri.path == '/old-page') { + navigationHistory.add('Replacing with /new-version'); + await goRouter.replace('/new-version'); + return const Block.stop(); + } + return const Allow(); + }, routes: [ GoRoute( path: '/home', - builder: - (_, __) => const Scaffold(body: Center(child: Text('Home'))), + builder: (_, __) => + const Scaffold(body: Center(child: Text('Home'))), ), GoRoute( path: '/old-page', - builder: - (_, __) => - const Scaffold(body: Center(child: Text('Old Page'))), + builder: (_, __) => + const Scaffold(body: Center(child: Text('Old Page'))), ), GoRoute( path: '/new-version', - builder: - (_, __) => - const Scaffold(body: Center(child: Text('New Version'))), + builder: (_, __) => + const Scaffold(body: Center(child: Text('New Version'))), ), ], ); @@ -562,51 +564,50 @@ void main() { router = GoRouter( initialLocation: '/home', - onEnter: ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - ) async { - navigationLog.add('Entering: ${next.uri.path}'); - - if (next.uri.path == '/outdated') { - navigationLog.add('Push replacing with /updated'); - await goRouter.pushReplacement('/updated'); - return const Block.stop(); - } - return const Allow(); - }, + onEnter: + ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + ) async { + navigationLog.add('Entering: ${next.uri.path}'); + + if (next.uri.path == '/outdated') { + navigationLog.add('Push replacing with /updated'); + await goRouter.pushReplacement('/updated'); + return const Block.stop(); + } + return const Allow(); + }, routes: [ GoRoute( path: '/home', - builder: - (_, __) => const Scaffold(body: Center(child: Text('Home'))), + builder: (_, __) => + const Scaffold(body: Center(child: Text('Home'))), ), GoRoute( path: '/outdated', - builder: - (_, __) => - const Scaffold(body: Center(child: Text('Outdated'))), + builder: (_, __) => + const Scaffold(body: Center(child: Text('Outdated'))), ), GoRoute( path: '/updated', - builder: - (_, __) => Scaffold( - body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - const Text('Updated'), - ElevatedButton( - onPressed: - () => router.go('/home'), // Use go instead of pop - child: const Text('Go Home'), - ), - ], + builder: (_, __) => Scaffold( + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Text('Updated'), + ElevatedButton( + onPressed: () => + router.go('/home'), // Use go instead of pop + child: const Text('Go Home'), ), - ), + ], ), + ), + ), ), ], ); @@ -644,8 +645,9 @@ void main() { StreamController<({String current, String next})>(); // Use broadcast stream for potentially multiple listeners/expects if needed, // although expectLater handles one listener well. - final Stream<({String current, String next})> paramsStream = - paramsSink.stream.asBroadcastStream(); + final Stream<({String current, String next})> paramsStream = paramsSink + .stream + .asBroadcastStream(); // Helper to navigate after sign-in button press void goToRedirect(GoRouter router, GoRouterState state) { @@ -662,74 +664,73 @@ void main() { router = GoRouter( initialLocation: '/home', - onEnter: ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - // Renamed parameter to avoid shadowing router variable - ) async { - // Log the navigation attempt state URIs - paramsSink.add(( - current: current.uri.toString(), - next: next.uri.toString(), - )); - - final bool isNavigatingToProtected = next.uri.path == '/protected'; - - // Allow navigation if not going to the protected route - if (!isNavigatingToProtected) { - return const Allow(); - } - - // Allow navigation if authenticated - if (await isAuthenticated()) { - return const Allow(); - } - - // If unauthenticated and going to protected route: - // 1. Redirect to sign-in using pushNamed, passing the intended destination - await goRouter.pushNamed( - 'sign-in', // Return type likely void or not needed - queryParameters: { - 'redirectTo': next.uri.toString(), // Pass the full next URI + onEnter: + ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + // Renamed parameter to avoid shadowing router variable + ) async { + // Log the navigation attempt state URIs + paramsSink.add(( + current: current.uri.toString(), + next: next.uri.toString(), + )); + + final bool isNavigatingToProtected = + next.uri.path == '/protected'; + + // Allow navigation if not going to the protected route + if (!isNavigatingToProtected) { + return const Allow(); + } + + // Allow navigation if authenticated + if (await isAuthenticated()) { + return const Allow(); + } + + // If unauthenticated and going to protected route: + // 1. Redirect to sign-in using pushNamed, passing the intended destination + await goRouter.pushNamed( + 'sign-in', // Return type likely void or not needed + queryParameters: { + 'redirectTo': next.uri.toString(), // Pass the full next URI + }, + ); + // 2. Block the original navigation to '/protected' + return const Block.stop(); }, - ); - // 2. Block the original navigation to '/protected' - return const Block.stop(); - }, routes: [ GoRoute( path: '/home', name: 'home', // Good practice to name routes - builder: - (_, __) => const Scaffold( - body: Center(child: Text('Home Screen')), - ), // Unique text + builder: (_, __) => const Scaffold( + body: Center(child: Text('Home Screen')), + ), // Unique text ), GoRoute( path: '/protected', name: 'protected', // Good practice to name routes - builder: - (_, __) => const Scaffold( - body: Center(child: Text('Protected Screen')), - ), // Unique text + builder: (_, __) => const Scaffold( + body: Center(child: Text('Protected Screen')), + ), // Unique text ), GoRoute( path: '/sign-in', name: 'sign-in', - builder: - (_, GoRouterState state) => Scaffold( - appBar: AppBar( - title: const Text('Sign In Screen Title'), // Unique text - ), - body: Center( - child: ElevatedButton( - child: const Text('Sign In Button'), // Unique text - onPressed: () => goToRedirect(router, state), - ), - ), + builder: (_, GoRouterState state) => Scaffold( + appBar: AppBar( + title: const Text('Sign In Screen Title'), // Unique text + ), + body: Center( + child: ElevatedButton( + child: const Text('Sign In Button'), // Unique text + onPressed: () => goToRedirect(router, state), ), + ), + ), ), ], ); @@ -818,59 +819,58 @@ void main() { router = GoRouter( initialLocation: '/start', - onEnter: ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - ) async { - final String targetPath = next.uri.path; - navigationChain.add('Entering: $targetPath'); - - // Execute a simpler navigation sequence - if (targetPath == '/multi-step') { - // Step 1: Go to a different route - navigationChain.add('Step 1: Go to /step-one'); - // We're blocking the original navigation and deferring the go - return Block.then(() => goRouter.go('/step-one')); - } + onEnter: + ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + ) async { + final String targetPath = next.uri.path; + navigationChain.add('Entering: $targetPath'); + + // Execute a simpler navigation sequence + if (targetPath == '/multi-step') { + // Step 1: Go to a different route + navigationChain.add('Step 1: Go to /step-one'); + // We're blocking the original navigation and deferring the go + return Block.then(() => goRouter.go('/step-one')); + } + + // When we reach step-one, mark test as complete + if (targetPath == '/step-one') { + navigationComplete.complete(); + } - // When we reach step-one, mark test as complete - if (targetPath == '/step-one') { - navigationComplete.complete(); - } - - return const Allow(); - }, + return const Allow(); + }, routes: [ GoRoute( path: '/start', - builder: - (_, __) => const Scaffold(body: Center(child: Text('Start'))), + builder: (_, __) => + const Scaffold(body: Center(child: Text('Start'))), ), GoRoute( path: '/multi-step', - builder: - (_, __) => - const Scaffold(body: Center(child: Text('Multi Step'))), + builder: (_, __) => + const Scaffold(body: Center(child: Text('Multi Step'))), ), GoRoute( path: '/step-one', - builder: - (_, __) => Scaffold( - body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - const Text('Step One'), - ElevatedButton( - onPressed: () => router.go('/start'), - child: const Text('Go Back to Start'), - ), - ], + builder: (_, __) => Scaffold( + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Text('Step One'), + ElevatedButton( + onPressed: () => router.go('/start'), + child: const Text('Go Back to Start'), ), - ), + ], ), + ), + ), ), ], ); @@ -912,41 +912,37 @@ void main() { // to avoid triggering the exception when navigating to the fallback route. router = GoRouter( initialLocation: '/error', - onException: ( - BuildContext context, - GoRouterState state, - GoRouter goRouter, - ) { - capturedError = state.error; - // Navigate to a safe fallback route. - goRouter.go('/fallback'); - completer.complete(); - }, - onEnter: ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - ) async { - // If the navigation target is '/fallback', allow it without throwing. - if (next.uri.path == '/fallback') { - return const Allow(); - } - // For any other target, throw an exception. - throw Exception('onEnter error triggered'); - }, + onException: + (BuildContext context, GoRouterState state, GoRouter goRouter) { + capturedError = state.error; + // Navigate to a safe fallback route. + goRouter.go('/fallback'); + completer.complete(); + }, + onEnter: + ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + ) async { + // If the navigation target is '/fallback', allow it without throwing. + if (next.uri.path == '/fallback') { + return const Allow(); + } + // For any other target, throw an exception. + throw Exception('onEnter error triggered'); + }, routes: [ GoRoute( path: '/error', - builder: - (_, __) => - const Scaffold(body: Center(child: Text('Error Page'))), + builder: (_, __) => + const Scaffold(body: Center(child: Text('Error Page'))), ), GoRoute( path: '/fallback', - builder: - (_, __) => - const Scaffold(body: Center(child: Text('Fallback Page'))), + builder: (_, __) => + const Scaffold(body: Center(child: Text('Fallback Page'))), ), ], ); @@ -1209,8 +1205,8 @@ void main() { routes: [ GoRoute( path: '/', - builder: - (_, __) => const Scaffold(body: Center(child: Text('Root'))), + builder: (_, __) => + const Scaffold(body: Center(child: Text('Root'))), ), GoRoute( path: '/article/:id', @@ -1253,14 +1249,13 @@ void main() { routes: [ GoRoute( path: '/parent', - builder: - (_, __) => const Scaffold(body: Center(child: Text('Parent'))), + builder: (_, __) => + const Scaffold(body: Center(child: Text('Parent'))), routes: [ GoRoute( path: 'child', - builder: - (_, __) => - const Scaffold(body: Center(child: Text('Child'))), + builder: (_, __) => + const Scaffold(body: Center(child: Text('Child'))), ), ], ), @@ -1287,20 +1282,21 @@ void main() { router = GoRouter( initialLocation: '/', - onEnter: ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - ) async { - seenNextPaths.add(next.uri.path); - return const Allow(); // don't block; let route-level redirect run - }, + onEnter: + ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + ) async { + seenNextPaths.add(next.uri.path); + return const Allow(); // don't block; let route-level redirect run + }, routes: [ GoRoute( path: '/', - builder: - (_, __) => const Scaffold(body: Center(child: Text('Root'))), + builder: (_, __) => + const Scaffold(body: Center(child: Text('Root'))), ), GoRoute( path: '/old', @@ -1310,8 +1306,8 @@ void main() { ), GoRoute( path: '/new', - builder: - (_, __) => const Scaffold(body: Center(child: Text('New'))), + builder: (_, __) => + const Scaffold(body: Center(child: Text('New'))), ), ], ); @@ -1355,13 +1351,13 @@ void main() { routes: [ GoRoute( path: '/home', - builder: - (_, __) => const Scaffold(body: Center(child: Text('Home'))), + builder: (_, __) => + const Scaffold(body: Center(child: Text('Home'))), ), GoRoute( path: '/boom', - builder: - (_, __) => const Scaffold(body: Center(child: Text('Boom'))), + builder: (_, __) => + const Scaffold(body: Center(child: Text('Boom'))), ), ], ); @@ -1415,19 +1411,18 @@ void main() { routes: [ GoRoute( path: '/start', - builder: - (_, __) => const Scaffold(body: Center(child: Text('Start'))), + builder: (_, __) => + const Scaffold(body: Center(child: Text('Start'))), ), GoRoute( path: '/blocked-once', - builder: - (_, __) => - const Scaffold(body: Center(child: Text('BlockedOnce'))), + builder: (_, __) => + const Scaffold(body: Center(child: Text('BlockedOnce'))), ), GoRoute( path: '/chain', - builder: - (_, __) => const Scaffold(body: Center(child: Text('Chain'))), + builder: (_, __) => + const Scaffold(body: Center(child: Text('Chain'))), ), ], ); diff --git a/packages/go_router/test/on_exit_test.dart b/packages/go_router/test/on_exit_test.dart index cf996954278..07f5be7e4bf 100644 --- a/packages/go_router/test/on_exit_test.dart +++ b/packages/go_router/test/on_exit_test.dart @@ -18,15 +18,13 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => - DummyScreen(key: home), + builder: (BuildContext context, GoRouterState state) => + DummyScreen(key: home), routes: [ GoRoute( path: '1', - builder: - (BuildContext context, GoRouterState state) => - DummyScreen(key: page1), + builder: (BuildContext context, GoRouterState state) => + DummyScreen(key: page1), onExit: (BuildContext context, GoRouterState state) { return allow; }, @@ -59,15 +57,13 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => - DummyScreen(key: home), + builder: (BuildContext context, GoRouterState state) => + DummyScreen(key: home), ), GoRoute( path: '/1', - builder: - (BuildContext context, GoRouterState state) => - DummyScreen(key: page1), + builder: (BuildContext context, GoRouterState state) => + DummyScreen(key: page1), onExit: (BuildContext context, GoRouterState state) { return allow; }, @@ -98,15 +94,13 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => - DummyScreen(key: home), + builder: (BuildContext context, GoRouterState state) => + DummyScreen(key: home), routes: [ GoRoute( path: '1', - builder: - (BuildContext context, GoRouterState state) => - DummyScreen(key: page1), + builder: (BuildContext context, GoRouterState state) => + DummyScreen(key: page1), onExit: (BuildContext context, GoRouterState state) async { return allow.future; }, @@ -147,15 +141,13 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => - DummyScreen(key: home), + builder: (BuildContext context, GoRouterState state) => + DummyScreen(key: home), ), GoRoute( path: '/1', - builder: - (BuildContext context, GoRouterState state) => - DummyScreen(key: page1), + builder: (BuildContext context, GoRouterState state) => + DummyScreen(key: page1), onExit: (BuildContext context, GoRouterState state) async { return allow.future; }, @@ -195,9 +187,8 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => - DummyScreen(key: home), + builder: (BuildContext context, GoRouterState state) => + DummyScreen(key: home), onExit: (BuildContext context, GoRouterState state) { return allow; }, @@ -222,9 +213,8 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => - DummyScreen(key: home), + builder: (BuildContext context, GoRouterState state) => + DummyScreen(key: home), onExit: (BuildContext context, GoRouterState state) async { return allow; }, @@ -252,9 +242,8 @@ void main() { routes: [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => - DummyScreen(key: home), + builder: (BuildContext context, GoRouterState state) => + DummyScreen(key: home), onExit: (BuildContext context, GoRouterState state) { return allow; }, @@ -286,15 +275,13 @@ void main() { final List routes = [ GoRoute( path: '/', - builder: - (BuildContext context, GoRouterState state) => - DummyScreen(key: home), + builder: (BuildContext context, GoRouterState state) => + DummyScreen(key: home), routes: [ GoRoute( path: '1', - builder: - (BuildContext context, GoRouterState state) => - DummyScreen(key: page1), + builder: (BuildContext context, GoRouterState state) => + DummyScreen(key: page1), onExit: (BuildContext context, GoRouterState state) { onExitState1 = state; return true; @@ -302,9 +289,8 @@ void main() { routes: [ GoRoute( path: '2', - builder: - (BuildContext context, GoRouterState state) => - DummyScreen(key: page2), + builder: (BuildContext context, GoRouterState state) => + DummyScreen(key: page2), onExit: (BuildContext context, GoRouterState state) { onExitState2 = state; return true; @@ -312,9 +298,8 @@ void main() { routes: [ GoRoute( path: '3', - builder: - (BuildContext context, GoRouterState state) => - DummyScreen(key: page3), + builder: (BuildContext context, GoRouterState state) => + DummyScreen(key: page3), onExit: (BuildContext context, GoRouterState state) { onExitState3 = state; return true; @@ -365,15 +350,13 @@ void main() { final List routes = [ GoRoute( path: '/route-0/:id0', - builder: - (BuildContext context, GoRouterState state) => - DummyScreen(key: page0), + builder: (BuildContext context, GoRouterState state) => + DummyScreen(key: page0), ), GoRoute( path: '/route-1/:id1', - builder: - (BuildContext context, GoRouterState state) => - DummyScreen(key: page1), + builder: (BuildContext context, GoRouterState state) => + DummyScreen(key: page1), onExit: (BuildContext context, GoRouterState state) { onExitState1 = state; return true; @@ -381,9 +364,8 @@ void main() { ), GoRoute( path: '/route-2/:id2', - builder: - (BuildContext context, GoRouterState state) => - DummyScreen(key: page2), + builder: (BuildContext context, GoRouterState state) => + DummyScreen(key: page2), onExit: (BuildContext context, GoRouterState state) { onExitState2 = state; return true; @@ -449,9 +431,8 @@ void main() { final List routes = [ GoRoute( path: '/route-0/:id0', - builder: - (BuildContext context, GoRouterState state) => - DummyScreen(key: page0), + builder: (BuildContext context, GoRouterState state) => + DummyScreen(key: page0), onExit: (BuildContext context, GoRouterState state) { onExitState0 = state; return true; @@ -459,9 +440,8 @@ void main() { ), GoRoute( path: '/route-1/:id1', - builder: - (BuildContext context, GoRouterState state) => - DummyScreen(key: page1), + builder: (BuildContext context, GoRouterState state) => + DummyScreen(key: page1), onExit: (BuildContext context, GoRouterState state) { onExitState1 = state; return true; @@ -469,9 +449,8 @@ void main() { ), GoRoute( path: '/route-2/:id2', - builder: - (BuildContext context, GoRouterState state) => - DummyScreen(key: page2), + builder: (BuildContext context, GoRouterState state) => + DummyScreen(key: page2), onExit: (BuildContext context, GoRouterState state) { onExitState2 = state; return true; diff --git a/packages/go_router/test/parser_test.dart b/packages/go_router/test/parser_test.dart index 838e85f2b6c..9520336768d 100644 --- a/packages/go_router/test/parser_test.dart +++ b/packages/go_router/test/parser_test.dart @@ -263,8 +263,9 @@ void main() { expect(matchList.uri.toString(), '/abc'); expect(matchList.matches.length, 3); - final RouteInformation restoredRouteInformation = - router.routeInformationParser.restoreRouteInformation(matchList)!; + final RouteInformation restoredRouteInformation = router + .routeInformationParser + .restoreRouteInformation(matchList)!; expect(restoredRouteInformation.uri.path, '/'); // Can restore back to original RouteMatchList. @@ -597,9 +598,8 @@ void main() { GoRoute( path: '/abc', builder: (_, __) => const Placeholder(), - redirect: - (BuildContext context, GoRouterState state) => - state.uri.toString(), + redirect: (BuildContext context, GoRouterState state) => + state.uri.toString(), ), ]; final GoRouteInformationParser parser = await createParser( diff --git a/packages/go_router/test/path_utils_test.dart b/packages/go_router/test/path_utils_test.dart index df3fd875fd4..32218ffcd47 100644 --- a/packages/go_router/test/path_utils_test.dart +++ b/packages/go_router/test/path_utils_test.dart @@ -111,8 +111,10 @@ void main() { test('concatenateUris', () { void verify(String pathA, String pathB, String expected) { - final String result = - concatenateUris(Uri.parse(pathA), Uri.parse(pathB)).toString(); + final String result = concatenateUris( + Uri.parse(pathA), + Uri.parse(pathB), + ).toString(); expect(result, expected); } diff --git a/packages/go_router/test/route_data_test.dart b/packages/go_router/test/route_data_test.dart index 96144c64c0b..61726de2649 100644 --- a/packages/go_router/test/route_data_test.dart +++ b/packages/go_router/test/route_data_test.dart @@ -193,8 +193,8 @@ class _StatefulShellRouteDataPageBuilder extends StatefulShellRouteData { final StatefulShellRoute _statefulShellRouteDataPageBuilder = StatefulShellRouteData.$route( - factory: - (GoRouterState state) => const _StatefulShellRouteDataPageBuilder(), + factory: (GoRouterState state) => + const _StatefulShellRouteDataPageBuilder(), branches: [ StatefulShellBranchData.$branch( routes: [ @@ -318,8 +318,8 @@ void main() { ) async { final List errors = []; - FlutterError.onError = - (FlutterErrorDetails details) => errors.add(details); + FlutterError.onError = (FlutterErrorDetails details) => + errors.add(details); const String errorText = 'Should be generated'; @@ -329,11 +329,10 @@ void main() { await tester.pumpWidget( MaterialApp( home: Builder( - builder: - (BuildContext context) => GestureDetector( - child: const Text('Tap'), - onTap: () => onTap(context), - ), + builder: (BuildContext context) => GestureDetector( + child: const Text('Tap'), + onTap: () => onTap(context), + ), ), ), ); @@ -403,8 +402,8 @@ void main() { final GoRoute routeWithDefaultCaseSensitivity = RelativeGoRouteData.$route( path: 'path', - factory: - (GoRouterState state) => const _RelativeGoRouteDataBuild(), + factory: (GoRouterState state) => + const _RelativeGoRouteDataBuild(), ); expect(routeWithDefaultCaseSensitivity.caseSensitive, true); @@ -418,8 +417,8 @@ void main() { RelativeGoRouteData.$route( path: 'path', caseSensitive: false, - factory: - (GoRouterState state) => const _RelativeGoRouteDataBuild(), + factory: (GoRouterState state) => + const _RelativeGoRouteDataBuild(), ); expect(routeWithDefaultCaseSensitivity.caseSensitive, false); @@ -431,8 +430,8 @@ void main() { ) async { final List errors = []; - FlutterError.onError = - (FlutterErrorDetails details) => errors.add(details); + FlutterError.onError = (FlutterErrorDetails details) => + errors.add(details); const String errorText = 'Should be generated'; @@ -442,11 +441,10 @@ void main() { await tester.pumpWidget( MaterialApp( home: Builder( - builder: - (BuildContext context) => GestureDetector( - child: const Text('Tap'), - onTap: () => onTap(context), - ), + builder: (BuildContext context) => GestureDetector( + child: const Text('Tap'), + onTap: () => onTap(context), + ), ), ), ); @@ -510,29 +508,25 @@ void main() { initialLocation: '/child/test', routes: [ ShellRouteData.$route( - factory: - (GoRouterState state) => - const _ShellRouteDataWithKey(Key('under-shell')), + factory: (GoRouterState state) => + const _ShellRouteDataWithKey(Key('under-shell')), routes: [ GoRouteData.$route( path: '/child', - factory: - (GoRouterState state) => - const _GoRouteDataBuildWithKey(Key('under')), + factory: (GoRouterState state) => + const _GoRouteDataBuildWithKey(Key('under')), routes: [ ShellRouteData.$route( - factory: - (GoRouterState state) => - const _ShellRouteDataWithKey(Key('above-shell')), + factory: (GoRouterState state) => + const _ShellRouteDataWithKey(Key('above-shell')), navigatorKey: inner, parentNavigatorKey: root, routes: [ GoRouteData.$route( parentNavigatorKey: inner, path: 'test', - factory: - (GoRouterState state) => - const _GoRouteDataBuildWithKey(Key('above')), + factory: (GoRouterState state) => + const _GoRouteDataBuildWithKey(Key('above')), ), ], ), @@ -620,8 +614,8 @@ void main() { final GlobalKey key = GlobalKey(); final StatefulShellRoute route = StatefulShellRouteData.$route( parentNavigatorKey: key, - factory: - (GoRouterState state) => const _StatefulShellRouteDataPageBuilder(), + factory: (GoRouterState state) => + const _StatefulShellRouteDataPageBuilder(), branches: [ StatefulShellBranchData.$branch( routes: [ @@ -673,9 +667,8 @@ void main() { routes: [ _goRouteDataBuildPage, StatefulShellRouteData.$route( - factory: - (GoRouterState state) => - const _StatefulShellRouteDataRedirectPage(), + factory: (GoRouterState state) => + const _StatefulShellRouteDataRedirectPage(), branches: [ StatefulShellBranchData.$branch( routes: [ diff --git a/packages/go_router/test/routing_config_test.dart b/packages/go_router/test/routing_config_test.dart index 6c64aeee057..01eb5330c7d 100644 --- a/packages/go_router/test/routing_config_test.dart +++ b/packages/go_router/test/routing_config_test.dart @@ -129,8 +129,8 @@ void main() { routes: [ GoRoute( path: '/', - builder: - (_, __) => StatefulTest(key: key, child: const Text('home')), + builder: (_, __) => + StatefulTest(key: key, child: const Text('home')), ), ], ), @@ -179,9 +179,8 @@ void main() { routes: [ GoRoute(path: '/', builder: (_, __) => const Text('home')), ], - builder: - (_, __, Widget widget) => - StatefulTest(key: key, child: widget), + builder: (_, __, Widget widget) => + StatefulTest(key: key, child: widget), ), ], ), @@ -204,8 +203,8 @@ void main() { GoRoute(path: '/', builder: (_, __) => const Text('home')), GoRoute(path: '/abc', builder: (_, __) => const Text('/abc')), ], - builder: - (_, __, Widget widget) => StatefulTest(key: key, child: widget), + builder: (_, __, Widget widget) => + StatefulTest(key: key, child: widget), ), ], ); diff --git a/packages/go_router/test/stateful_shell_route_system_back_test.dart b/packages/go_router/test/stateful_shell_route_system_back_test.dart index 4df7d89f70e..834af97b01b 100644 --- a/packages/go_router/test/stateful_shell_route_system_back_test.dart +++ b/packages/go_router/test/stateful_shell_route_system_back_test.dart @@ -117,13 +117,14 @@ class _TestAppState extends State<_TestApp> { }, routes: [ StatefulShellRoute.indexedStack( - builder: ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - return navigationShell; - }, + builder: + ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + return navigationShell; + }, branches: [ StatefulShellBranch( routes: [ diff --git a/packages/go_router/test/test_helpers.dart b/packages/go_router/test/test_helpers.dart index b48235fea12..4f30e8e107c 100644 --- a/packages/go_router/test/test_helpers.dart +++ b/packages/go_router/test/test_helpers.dart @@ -196,8 +196,9 @@ Future createRouter( addTearDown(goRouter.dispose); await tester.pumpWidget( MaterialApp.router( - restorationScopeId: - restorationScopeId != null ? '$restorationScopeId-root' : null, + restorationScopeId: restorationScopeId != null + ? '$restorationScopeId-root' + : null, routerConfig: goRouter, ), ); @@ -230,8 +231,9 @@ Future createRouterWithRoutingConfig( addTearDown(goRouter.dispose); await tester.pumpWidget( MaterialApp.router( - restorationScopeId: - restorationScopeId != null ? '$restorationScopeId-root' : null, + restorationScopeId: restorationScopeId != null + ? '$restorationScopeId-root' + : null, routerConfig: goRouter, ), ); @@ -375,13 +377,14 @@ GoRouterPageBuilder createPageBuilder({ (BuildContext context, GoRouterState state) => MaterialPage(restorationId: restorationId, child: child); -StatefulShellRouteBuilder mockStackedShellBuilder = ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, -) { - return navigationShell; -}; +StatefulShellRouteBuilder mockStackedShellBuilder = + ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + return navigationShell; + }; /// A routing config that is never going to change. class ConstantRoutingConfig extends ValueListenable { @@ -426,8 +429,8 @@ class SimpleDependencyProvider extends InheritedNotifier { }) : super(notifier: dependency); static SimpleDependency of(BuildContext context) { - final SimpleDependencyProvider result = - context.dependOnInheritedWidgetOfExactType()!; + final SimpleDependencyProvider result = context + .dependOnInheritedWidgetOfExactType()!; return result.notifier!; } } diff --git a/packages/go_router/tool/run_tests.dart b/packages/go_router/tool/run_tests.dart index 7a41e08c840..6fa363072dd 100644 --- a/packages/go_router/tool/run_tests.dart +++ b/packages/go_router/tool/run_tests.dart @@ -19,8 +19,9 @@ import 'package:path/path.dart' as p; // that references `go_router`, and running `dart fix --compare-to-golden` // on the temp directory. Future main(List args) async { - final Directory goRouterPackageRoot = - File.fromUri(Platform.script).parent.parent; + final Directory goRouterPackageRoot = File.fromUri( + Platform.script, + ).parent.parent; final Directory testTempDir = await Directory.systemTemp.createTemp(); @@ -72,7 +73,8 @@ Future _prepareTemplate({ // The pubspec.yaml file to create. final File targetPubspecFile = File(p.join(testTempDir.path, 'pubspec.yaml')); - final String targetYaml = ''' + final String targetYaml = + ''' name: test_fixes publish_to: "none" version: 1.0.0 diff --git a/packages/go_router_builder/CHANGELOG.md b/packages/go_router_builder/CHANGELOG.md index 895a4e5536a..74d7ed7ce1d 100644 --- a/packages/go_router_builder/CHANGELOG.md +++ b/packages/go_router_builder/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. + ## 4.1.1 - Allow `analyzer: '>=7.4.0 <9.0.0'`. diff --git a/packages/go_router_builder/README.md b/packages/go_router_builder/README.md index a410250ced6..c88879faefc 100644 --- a/packages/go_router_builder/README.md +++ b/packages/go_router_builder/README.md @@ -399,14 +399,15 @@ class FancyRoute extends GoRouteData with $FancyRoute { return CustomTransitionPage( key: state.pageKey, child: const MyPage(), - transitionsBuilder: ( - BuildContext context, - Animation animation, - Animation secondaryAnimation, - Widget child, - ) { - return RotationTransition(turns: animation, child: child); - }, + transitionsBuilder: + ( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + Widget child, + ) { + return RotationTransition(turns: animation, child: child); + }, ); } } diff --git a/packages/go_router_builder/example/lib/all_extension_types.g.dart b/packages/go_router_builder/example/lib/all_extension_types.g.dart index 93e56733717..3fd882af5ef 100644 --- a/packages/go_router_builder/example/lib/all_extension_types.g.dart +++ b/packages/go_router_builder/example/lib/all_extension_types.g.dart @@ -143,8 +143,8 @@ mixin $BoolExtensionRoute on GoRouteData { queryParams: { if (_self.boolField != null) 'bool-field': _self.boolField!.toString(), if (_self.boolFieldWithDefaultValue != const BoolExtension(true)) - 'bool-field-with-default-value': - _self.boolFieldWithDefaultValue.toString(), + 'bool-field-with-default-value': _self.boolFieldWithDefaultValue + .toString(), }, ); @@ -201,24 +201,23 @@ mixin $DateTimeExtensionRoute on GoRouteData { } mixin $DoubleExtensionRoute on GoRouteData { - static DoubleExtensionRoute _fromState(GoRouterState state) => - DoubleExtensionRoute( - requiredDoubleField: - double.parse(state.pathParameters['requiredDoubleField']!) - as DoubleExtension, - doubleField: - double.tryParse(state.uri.queryParameters['double-field'] ?? '') - as DoubleExtension?, - doubleFieldWithDefaultValue: - double.tryParse( - state - .uri - .queryParameters['double-field-with-default-value'] ?? - '', - ) - as DoubleExtension? ?? - const DoubleExtension(1.0), - ); + static DoubleExtensionRoute _fromState( + GoRouterState state, + ) => DoubleExtensionRoute( + requiredDoubleField: + double.parse(state.pathParameters['requiredDoubleField']!) + as DoubleExtension, + doubleField: + double.tryParse(state.uri.queryParameters['double-field'] ?? '') + as DoubleExtension?, + doubleFieldWithDefaultValue: + double.tryParse( + state.uri.queryParameters['double-field-with-default-value'] ?? + '', + ) + as DoubleExtension? ?? + const DoubleExtension(1.0), + ); DoubleExtensionRoute get _self => this as DoubleExtensionRoute; @@ -229,8 +228,8 @@ mixin $DoubleExtensionRoute on GoRouteData { if (_self.doubleField != null) 'double-field': _self.doubleField!.toString(), if (_self.doubleFieldWithDefaultValue != const DoubleExtension(1.0)) - 'double-field-with-default-value': - _self.doubleFieldWithDefaultValue.toString(), + 'double-field-with-default-value': _self.doubleFieldWithDefaultValue + .toString(), }, ); @@ -271,8 +270,8 @@ mixin $IntExtensionRoute on GoRouteData { queryParams: { if (_self.intField != null) 'int-field': _self.intField!.toString(), if (_self.intFieldWithDefaultValue != const IntExtension(1)) - 'int-field-with-default-value': - _self.intFieldWithDefaultValue.toString(), + 'int-field-with-default-value': _self.intFieldWithDefaultValue + .toString(), }, ); @@ -313,8 +312,8 @@ mixin $NumExtensionRoute on GoRouteData { queryParams: { if (_self.numField != null) 'num-field': _self.numField!.toString(), if (_self.numFieldWithDefaultValue != const NumExtension(1)) - 'num-field-with-default-value': - _self.numFieldWithDefaultValue.toString(), + 'num-field-with-default-value': _self.numFieldWithDefaultValue + .toString(), }, ); diff --git a/packages/go_router_builder/example/lib/all_types.dart b/packages/go_router_builder/example/lib/all_types.dart index 66bc60c8f55..d984043e386 100644 --- a/packages/go_router_builder/example/lib/all_types.dart +++ b/packages/go_router_builder/example/lib/all_types.dart @@ -598,24 +598,23 @@ class IterablePage extends StatelessWidget { Widget build(BuildContext context) { return BasePage( dataTitle: dataTitle, - queryParamWithDefaultValue: - ?>{ - 'intIterableField': intIterableField, - 'intListField': intListField, - 'intSetField': intSetField, - 'doubleIterableField': doubleIterableField, - 'doubleListField': doubleListField, - 'doubleSetField': doubleSetField, - 'stringIterableField': stringIterableField, - 'stringListField': stringListField, - 'stringSetField': stringSetField, - 'boolIterableField': boolIterableField, - 'boolListField': boolListField, - 'boolSetField': boolSetField, - 'enumIterableField': enumIterableField, - 'enumListField': enumListField, - 'enumSetField': enumSetField, - }.toString(), + queryParamWithDefaultValue: ?>{ + 'intIterableField': intIterableField, + 'intListField': intListField, + 'intSetField': intSetField, + 'doubleIterableField': doubleIterableField, + 'doubleListField': doubleListField, + 'doubleSetField': doubleSetField, + 'stringIterableField': stringIterableField, + 'stringListField': stringListField, + 'stringSetField': stringSetField, + 'boolIterableField': boolIterableField, + 'boolListField': boolListField, + 'boolSetField': boolSetField, + 'enumIterableField': enumIterableField, + 'enumListField': enumListField, + 'enumSetField': enumSetField, + }.toString(), ); } } diff --git a/packages/go_router_builder/example/lib/all_types.g.dart b/packages/go_router_builder/example/lib/all_types.g.dart index a4f90746beb..81f90bb61d6 100644 --- a/packages/go_router_builder/example/lib/all_types.g.dart +++ b/packages/go_router_builder/example/lib/all_types.g.dart @@ -154,8 +154,8 @@ mixin $BoolRoute on GoRouteData { queryParams: { if (_self.boolField != null) 'bool-field': _self.boolField!.toString(), if (_self.boolFieldWithDefaultValue != true) - 'bool-field-with-default-value': - _self.boolFieldWithDefaultValue.toString(), + 'bool-field-with-default-value': _self.boolFieldWithDefaultValue + .toString(), }, ); @@ -238,8 +238,8 @@ mixin $DoubleRoute on GoRouteData { if (_self.doubleField != null) 'double-field': _self.doubleField!.toString(), if (_self.doubleFieldWithDefaultValue != 1.0) - 'double-field-with-default-value': - _self.doubleFieldWithDefaultValue.toString(), + 'double-field-with-default-value': _self.doubleFieldWithDefaultValue + .toString(), }, ); @@ -282,8 +282,8 @@ mixin $IntRoute on GoRouteData { queryParams: { if (_self.intField != null) 'int-field': _self.intField!.toString(), if (_self.intFieldWithDefaultValue != 1) - 'int-field-with-default-value': - _self.intFieldWithDefaultValue.toString(), + 'int-field-with-default-value': _self.intFieldWithDefaultValue + .toString(), }, ); @@ -326,8 +326,8 @@ mixin $NumRoute on GoRouteData { queryParams: { if (_self.numField != null) 'num-field': _self.numField!.toString(), if (_self.numFieldWithDefaultValue != 1) - 'num-field-with-default-value': - _self.numFieldWithDefaultValue.toString(), + 'num-field-with-default-value': _self.numFieldWithDefaultValue + .toString(), }, ); @@ -347,10 +347,9 @@ mixin $NumRoute on GoRouteData { mixin $EnumRoute on GoRouteData { static EnumRoute _fromState(GoRouterState state) => EnumRoute( - requiredEnumField: - _$PersonDetailsEnumMap._$fromName( - state.pathParameters['requiredEnumField']!, - )!, + requiredEnumField: _$PersonDetailsEnumMap._$fromName( + state.pathParameters['requiredEnumField']!, + )!, enumField: _$convertMapValue( 'enum-field', state.uri.queryParameters, @@ -401,10 +400,9 @@ const _$PersonDetailsEnumMap = { mixin $EnhancedEnumRoute on GoRouteData { static EnhancedEnumRoute _fromState(GoRouterState state) => EnhancedEnumRoute( - requiredEnumField: - _$SportDetailsEnumMap._$fromName( - state.pathParameters['requiredEnumField']!, - )!, + requiredEnumField: _$SportDetailsEnumMap._$fromName( + state.pathParameters['requiredEnumField']!, + )!, enumField: _$convertMapValue( 'enum-field', state.uri.queryParameters, @@ -525,84 +523,71 @@ mixin $UriRoute on GoRouteData { mixin $IterableRoute on GoRouteData { static IterableRoute _fromState(GoRouterState state) => IterableRoute( - intIterableField: - state.uri.queryParametersAll['int-iterable-field'] - ?.map(int.parse) - .cast(), - doubleIterableField: - state.uri.queryParametersAll['double-iterable-field'] - ?.map(double.parse) - .cast(), + intIterableField: state.uri.queryParametersAll['int-iterable-field'] + ?.map(int.parse) + .cast(), + doubleIterableField: state.uri.queryParametersAll['double-iterable-field'] + ?.map(double.parse) + .cast(), stringIterableField: state.uri.queryParametersAll['string-iterable-field'] ?.map((e) => e), - boolIterableField: - state.uri.queryParametersAll['bool-iterable-field'] - ?.map(_$boolConverter) - .cast(), - enumIterableField: - state.uri.queryParametersAll['enum-iterable-field'] - ?.map(_$SportDetailsEnumMap._$fromName) - .cast(), - enumOnlyInIterableField: - state.uri.queryParametersAll['enum-only-in-iterable-field'] - ?.map(_$CookingRecipeEnumMap._$fromName) - .cast(), - intListField: - state.uri.queryParametersAll['int-list-field'] - ?.map(int.parse) - .cast() - .toList(), - doubleListField: - state.uri.queryParametersAll['double-list-field'] - ?.map(double.parse) - .cast() - .toList(), - stringListField: - state.uri.queryParametersAll['string-list-field'] - ?.map((e) => e) - .toList(), - boolListField: - state.uri.queryParametersAll['bool-list-field'] - ?.map(_$boolConverter) - .cast() - .toList(), - enumListField: - state.uri.queryParametersAll['enum-list-field'] - ?.map(_$SportDetailsEnumMap._$fromName) - .cast() - .toList(), - enumOnlyInListField: - state.uri.queryParametersAll['enum-only-in-list-field'] - ?.map(_$CookingRecipeEnumMap._$fromName) - .cast() - .toList(), - intSetField: - state.uri.queryParametersAll['int-set-field'] - ?.map(int.parse) - .cast() - .toSet(), - doubleSetField: - state.uri.queryParametersAll['double-set-field'] - ?.map(double.parse) - .cast() - .toSet(), - stringSetField: - state.uri.queryParametersAll['string-set-field']?.map((e) => e).toSet(), - boolSetField: - state.uri.queryParametersAll['bool-set-field'] - ?.map(_$boolConverter) - .cast() - .toSet(), - enumSetField: - state.uri.queryParametersAll['enum-set-field'] - ?.map(_$SportDetailsEnumMap._$fromName) - .cast() - .toSet(), - enumOnlyInSetField: - state.uri.queryParametersAll['enum-only-in-set-field'] - ?.map(_$CookingRecipeEnumMap._$fromName) - .cast() - .toSet(), + boolIterableField: state.uri.queryParametersAll['bool-iterable-field'] + ?.map(_$boolConverter) + .cast(), + enumIterableField: state.uri.queryParametersAll['enum-iterable-field'] + ?.map(_$SportDetailsEnumMap._$fromName) + .cast(), + enumOnlyInIterableField: state + .uri + .queryParametersAll['enum-only-in-iterable-field'] + ?.map(_$CookingRecipeEnumMap._$fromName) + .cast(), + intListField: state.uri.queryParametersAll['int-list-field'] + ?.map(int.parse) + .cast() + .toList(), + doubleListField: state.uri.queryParametersAll['double-list-field'] + ?.map(double.parse) + .cast() + .toList(), + stringListField: state.uri.queryParametersAll['string-list-field'] + ?.map((e) => e) + .toList(), + boolListField: state.uri.queryParametersAll['bool-list-field'] + ?.map(_$boolConverter) + .cast() + .toList(), + enumListField: state.uri.queryParametersAll['enum-list-field'] + ?.map(_$SportDetailsEnumMap._$fromName) + .cast() + .toList(), + enumOnlyInListField: state.uri.queryParametersAll['enum-only-in-list-field'] + ?.map(_$CookingRecipeEnumMap._$fromName) + .cast() + .toList(), + intSetField: state.uri.queryParametersAll['int-set-field'] + ?.map(int.parse) + .cast() + .toSet(), + doubleSetField: state.uri.queryParametersAll['double-set-field'] + ?.map(double.parse) + .cast() + .toSet(), + stringSetField: state.uri.queryParametersAll['string-set-field'] + ?.map((e) => e) + .toSet(), + boolSetField: state.uri.queryParametersAll['bool-set-field'] + ?.map(_$boolConverter) + .cast() + .toSet(), + enumSetField: state.uri.queryParametersAll['enum-set-field'] + ?.map(_$SportDetailsEnumMap._$fromName) + .cast() + .toSet(), + enumOnlyInSetField: state.uri.queryParametersAll['enum-only-in-set-field'] + ?.map(_$CookingRecipeEnumMap._$fromName) + .cast() + .toSet(), ); IterableRoute get _self => this as IterableRoute; @@ -612,62 +597,67 @@ mixin $IterableRoute on GoRouteData { '/iterable-route', queryParams: { if (_self.intIterableField != null) - 'int-iterable-field': - _self.intIterableField?.map((e) => e.toString()).toList(), + 'int-iterable-field': _self.intIterableField + ?.map((e) => e.toString()) + .toList(), if (_self.doubleIterableField != null) - 'double-iterable-field': - _self.doubleIterableField?.map((e) => e.toString()).toList(), + 'double-iterable-field': _self.doubleIterableField + ?.map((e) => e.toString()) + .toList(), if (_self.stringIterableField != null) - 'string-iterable-field': - _self.stringIterableField?.map((e) => e).toList(), + 'string-iterable-field': _self.stringIterableField + ?.map((e) => e) + .toList(), if (_self.boolIterableField != null) - 'bool-iterable-field': - _self.boolIterableField?.map((e) => e.toString()).toList(), + 'bool-iterable-field': _self.boolIterableField + ?.map((e) => e.toString()) + .toList(), if (_self.enumIterableField != null) - 'enum-iterable-field': - _self.enumIterableField - ?.map((e) => _$SportDetailsEnumMap[e]) - .toList(), + 'enum-iterable-field': _self.enumIterableField + ?.map((e) => _$SportDetailsEnumMap[e]) + .toList(), if (_self.enumOnlyInIterableField != null) - 'enum-only-in-iterable-field': - _self.enumOnlyInIterableField - ?.map((e) => _$CookingRecipeEnumMap[e]) - .toList(), + 'enum-only-in-iterable-field': _self.enumOnlyInIterableField + ?.map((e) => _$CookingRecipeEnumMap[e]) + .toList(), if (_self.intListField != null) 'int-list-field': _self.intListField?.map((e) => e.toString()).toList(), if (_self.doubleListField != null) - 'double-list-field': - _self.doubleListField?.map((e) => e.toString()).toList(), + 'double-list-field': _self.doubleListField + ?.map((e) => e.toString()) + .toList(), if (_self.stringListField != null) 'string-list-field': _self.stringListField?.map((e) => e).toList(), if (_self.boolListField != null) - 'bool-list-field': - _self.boolListField?.map((e) => e.toString()).toList(), + 'bool-list-field': _self.boolListField + ?.map((e) => e.toString()) + .toList(), if (_self.enumListField != null) - 'enum-list-field': - _self.enumListField?.map((e) => _$SportDetailsEnumMap[e]).toList(), + 'enum-list-field': _self.enumListField + ?.map((e) => _$SportDetailsEnumMap[e]) + .toList(), if (_self.enumOnlyInListField != null) - 'enum-only-in-list-field': - _self.enumOnlyInListField - ?.map((e) => _$CookingRecipeEnumMap[e]) - .toList(), + 'enum-only-in-list-field': _self.enumOnlyInListField + ?.map((e) => _$CookingRecipeEnumMap[e]) + .toList(), if (_self.intSetField != null) 'int-set-field': _self.intSetField?.map((e) => e.toString()).toList(), if (_self.doubleSetField != null) - 'double-set-field': - _self.doubleSetField?.map((e) => e.toString()).toList(), + 'double-set-field': _self.doubleSetField + ?.map((e) => e.toString()) + .toList(), if (_self.stringSetField != null) 'string-set-field': _self.stringSetField?.map((e) => e).toList(), if (_self.boolSetField != null) 'bool-set-field': _self.boolSetField?.map((e) => e.toString()).toList(), if (_self.enumSetField != null) - 'enum-set-field': - _self.enumSetField?.map((e) => _$SportDetailsEnumMap[e]).toList(), + 'enum-set-field': _self.enumSetField + ?.map((e) => _$SportDetailsEnumMap[e]) + .toList(), if (_self.enumOnlyInSetField != null) - 'enum-only-in-set-field': - _self.enumOnlyInSetField - ?.map((e) => _$CookingRecipeEnumMap[e]) - .toList(), + 'enum-only-in-set-field': _self.enumOnlyInSetField + ?.map((e) => _$CookingRecipeEnumMap[e]) + .toList(), }, ); @@ -787,50 +777,57 @@ mixin $IterableRouteWithDefaultValues on GoRouteData { '/iterable-route-with-default-values', queryParams: { if (!_$iterablesEqual(_self.intIterableField, const [0])) - 'int-iterable-field': - _self.intIterableField.map((e) => e.toString()).toList(), + 'int-iterable-field': _self.intIterableField + .map((e) => e.toString()) + .toList(), if (!_$iterablesEqual(_self.doubleIterableField, const [0, 1, 2])) - 'double-iterable-field': - _self.doubleIterableField.map((e) => e.toString()).toList(), + 'double-iterable-field': _self.doubleIterableField + .map((e) => e.toString()) + .toList(), if (!_$iterablesEqual(_self.stringIterableField, const [ 'defaultValue', ])) - 'string-iterable-field': - _self.stringIterableField.map((e) => e).toList(), + 'string-iterable-field': _self.stringIterableField + .map((e) => e) + .toList(), if (!_$iterablesEqual(_self.boolIterableField, const [false])) - 'bool-iterable-field': - _self.boolIterableField.map((e) => e.toString()).toList(), + 'bool-iterable-field': _self.boolIterableField + .map((e) => e.toString()) + .toList(), if (!_$iterablesEqual(_self.enumIterableField, const [ SportDetails.tennis, SportDetails.hockey, ])) - 'enum-iterable-field': - _self.enumIterableField - .map((e) => _$SportDetailsEnumMap[e]) - .toList(), + 'enum-iterable-field': _self.enumIterableField + .map((e) => _$SportDetailsEnumMap[e]) + .toList(), if (!_$iterablesEqual(_self.intListField, const [0])) 'int-list-field': _self.intListField.map((e) => e.toString()).toList(), if (!_$iterablesEqual(_self.doubleListField, const [1, 2, 3])) - 'double-list-field': - _self.doubleListField.map((e) => e.toString()).toList(), + 'double-list-field': _self.doubleListField + .map((e) => e.toString()) + .toList(), if (!_$iterablesEqual(_self.stringListField, const [ 'defaultValue0', 'defaultValue1', ])) 'string-list-field': _self.stringListField.map((e) => e).toList(), if (!_$iterablesEqual(_self.boolListField, const [true])) - 'bool-list-field': - _self.boolListField.map((e) => e.toString()).toList(), + 'bool-list-field': _self.boolListField + .map((e) => e.toString()) + .toList(), if (!_$iterablesEqual(_self.enumListField, const [ SportDetails.football, ])) - 'enum-list-field': - _self.enumListField.map((e) => _$SportDetailsEnumMap[e]).toList(), + 'enum-list-field': _self.enumListField + .map((e) => _$SportDetailsEnumMap[e]) + .toList(), if (!_$iterablesEqual(_self.intSetField, const {0, 1})) 'int-set-field': _self.intSetField.map((e) => e.toString()).toList(), if (!_$iterablesEqual(_self.doubleSetField, const {})) - 'double-set-field': - _self.doubleSetField.map((e) => e.toString()).toList(), + 'double-set-field': _self.doubleSetField + .map((e) => e.toString()) + .toList(), if (!_$iterablesEqual(_self.stringSetField, const { 'defaultValue', })) @@ -840,8 +837,9 @@ mixin $IterableRouteWithDefaultValues on GoRouteData { if (!_$iterablesEqual(_self.enumSetField, const { SportDetails.hockey, })) - 'enum-set-field': - _self.enumSetField.map((e) => _$SportDetailsEnumMap[e]).toList(), + 'enum-set-field': _self.enumSetField + .map((e) => _$SportDetailsEnumMap[e]) + .toList(), }, ); diff --git a/packages/go_router_builder/example/lib/extra_example.dart b/packages/go_router_builder/example/lib/extra_example.dart index 345b7902078..9c38f35b9ae 100644 --- a/packages/go_router_builder/example/lib/extra_example.dart +++ b/packages/go_router_builder/example/lib/extra_example.dart @@ -101,13 +101,13 @@ class Splash extends StatelessWidget { children: [ const Placeholder(), ElevatedButton( - onPressed: - () => const RequiredExtraRoute($extra: Extra(1)).go(context), + onPressed: () => + const RequiredExtraRoute($extra: Extra(1)).go(context), child: const Text('Required Extra'), ), ElevatedButton( - onPressed: - () => const OptionalExtraRoute($extra: Extra(2)).go(context), + onPressed: () => + const OptionalExtraRoute($extra: Extra(2)).go(context), child: const Text('Optional Extra'), ), ElevatedButton( diff --git a/packages/go_router_builder/example/lib/go_relative.dart b/packages/go_router_builder/example/lib/go_relative.dart index dbbb09cb42b..988df38c0c7 100644 --- a/packages/go_router_builder/example/lib/go_relative.dart +++ b/packages/go_router_builder/example/lib/go_relative.dart @@ -152,10 +152,9 @@ class DetailsScreen extends StatelessWidget { child: const Text('Go back'), ), ElevatedButton( - onPressed: - () => const SettingsRoute( - settingId: 'SettingsId', - ).goRelative(context), + onPressed: () => const SettingsRoute( + settingId: 'SettingsId', + ).goRelative(context), child: const Text('Go to the Settings screen'), ), ], diff --git a/packages/go_router_builder/example/lib/json_nested_example.dart b/packages/go_router_builder/example/lib/json_nested_example.dart index a327ead00f9..f88f8770b2a 100644 --- a/packages/go_router_builder/example/lib/json_nested_example.dart +++ b/packages/go_router_builder/example/lib/json_nested_example.dart @@ -58,10 +58,9 @@ class HomeScreen extends StatelessWidget { for (final JsonExample json in jsonData) ListTile( title: Text(json.name), - onTap: - () => JsonRoute( - JsonExampleNested(child: json), - ).go(context), + onTap: () => JsonRoute( + JsonExampleNested(child: json), + ).go(context), ), ], ), diff --git a/packages/go_router_builder/example/lib/main.dart b/packages/go_router_builder/example/lib/main.dart index 63869f91d8c..a4ce0d9cca2 100644 --- a/packages/go_router_builder/example/lib/main.dart +++ b/packages/go_router_builder/example/lib/main.dart @@ -263,21 +263,16 @@ class PersonScreen extends StatelessWidget { ListTile( title: Text('${entry.key.name} - ${entry.value}'), trailing: OutlinedButton( - onPressed: - () => PersonDetailsRoute( - family.id, - person.id, - entry.key, - $extra: ++_extraClickCount, - ).go(context), + onPressed: () => PersonDetailsRoute( + family.id, + person.id, + entry.key, + $extra: ++_extraClickCount, + ).go(context), child: const Text('With extra...'), ), - onTap: - () => PersonDetailsRoute( - family.id, - person.id, - entry.key, - ).go(context), + onTap: () => + PersonDetailsRoute(family.id, person.id, entry.key).go(context), ), ], ), diff --git a/packages/go_router_builder/example/lib/on_exit_example.dart b/packages/go_router_builder/example/lib/on_exit_example.dart index 1b286fd02e4..155f6719535 100644 --- a/packages/go_router_builder/example/lib/on_exit_example.dart +++ b/packages/go_router_builder/example/lib/on_exit_example.dart @@ -41,20 +41,19 @@ class SubRoute extends GoRouteData with $SubRoute { Future onExit(BuildContext context, GoRouterState state) async { final bool? confirmed = await showDialog( context: context, - builder: - (_) => AlertDialog( - content: const Text('Are you sure to leave this page?'), - actions: [ - TextButton( - onPressed: () => Navigator.of(context).pop(false), - child: const Text('Cancel'), - ), - ElevatedButton( - onPressed: () => Navigator.of(context).pop(true), - child: const Text('Confirm'), - ), - ], + builder: (_) => AlertDialog( + content: const Text('Are you sure to leave this page?'), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(false), + child: const Text('Cancel'), ), + ElevatedButton( + onPressed: () => Navigator.of(context).pop(true), + child: const Text('Confirm'), + ), + ], + ), ); return confirmed ?? false; } diff --git a/packages/go_router_builder/example/lib/readme_excerpts.dart b/packages/go_router_builder/example/lib/readme_excerpts.dart index a48566a0253..bbb1d5b5525 100644 --- a/packages/go_router_builder/example/lib/readme_excerpts.dart +++ b/packages/go_router_builder/example/lib/readme_excerpts.dart @@ -356,14 +356,15 @@ class FancyRoute extends GoRouteData with $FancyRoute { return CustomTransitionPage( key: state.pageKey, child: const MyPage(), - transitionsBuilder: ( - BuildContext context, - Animation animation, - Animation secondaryAnimation, - Widget child, - ) { - return RotationTransition(turns: animation, child: child); - }, + transitionsBuilder: + ( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + Widget child, + ) { + return RotationTransition(turns: animation, child: child); + }, ); } } diff --git a/packages/go_router_builder/example/lib/stateful_shell_route_example.dart b/packages/go_router_builder/example/lib/stateful_shell_route_example.dart index b9c6394da74..b291ff166ad 100644 --- a/packages/go_router_builder/example/lib/stateful_shell_route_example.dart +++ b/packages/go_router_builder/example/lib/stateful_shell_route_example.dart @@ -180,18 +180,17 @@ class AnimatedBranchContainer extends StatelessWidget { @override Widget build(BuildContext context) { return Stack( - children: - children.mapIndexed((int index, Widget navigator) { - return AnimatedScale( - scale: index == currentIndex ? 1 : 1.5, - duration: const Duration(milliseconds: 400), - child: AnimatedOpacity( - opacity: index == currentIndex ? 1 : 0, - duration: const Duration(milliseconds: 400), - child: _branchNavigatorWrapper(index, navigator), - ), - ); - }).toList(), + children: children.mapIndexed((int index, Widget navigator) { + return AnimatedScale( + scale: index == currentIndex ? 1 : 1.5, + duration: const Duration(milliseconds: 400), + child: AnimatedOpacity( + opacity: index == currentIndex ? 1 : 0, + duration: const Duration(milliseconds: 400), + child: _branchNavigatorWrapper(index, navigator), + ), + ); + }).toList(), ); } diff --git a/packages/go_router_builder/example/lib/stateful_shell_route_initial_location_example.dart b/packages/go_router_builder/example/lib/stateful_shell_route_initial_location_example.dart index 8b5eae7e670..0f51f815cb7 100644 --- a/packages/go_router_builder/example/lib/stateful_shell_route_initial_location_example.dart +++ b/packages/go_router_builder/example/lib/stateful_shell_route_initial_location_example.dart @@ -163,7 +163,9 @@ class NotificationsPageView extends StatelessWidget { Tab( child: Text('Latest', style: TextStyle(color: Colors.black87)), ), - Tab(child: Text('Old', style: TextStyle(color: Colors.black87))), + Tab( + child: Text('Old', style: TextStyle(color: Colors.black87)), + ), Tab( child: Text('Archive', style: TextStyle(color: Colors.black87)), ), diff --git a/packages/go_router_builder/example/lib/stateful_shell_route_initial_location_example.g.dart b/packages/go_router_builder/example/lib/stateful_shell_route_initial_location_example.g.dart index 89298e956a2..690ffbdf9c6 100644 --- a/packages/go_router_builder/example/lib/stateful_shell_route_initial_location_example.g.dart +++ b/packages/go_router_builder/example/lib/stateful_shell_route_initial_location_example.g.dart @@ -66,10 +66,9 @@ mixin $HomeRouteData on GoRouteData { mixin $NotificationsRouteData on GoRouteData { static NotificationsRouteData _fromState(GoRouterState state) => NotificationsRouteData( - section: - _$NotificationsPageSectionEnumMap._$fromName( - state.pathParameters['section']!, - )!, + section: _$NotificationsPageSectionEnumMap._$fromName( + state.pathParameters['section']!, + )!, ); NotificationsRouteData get _self => this as NotificationsRouteData; diff --git a/packages/go_router_builder/example/pubspec.yaml b/packages/go_router_builder/example/pubspec.yaml index a582818bdbf..e1ea3ab9f53 100644 --- a/packages/go_router_builder/example/pubspec.yaml +++ b/packages/go_router_builder/example/pubspec.yaml @@ -3,7 +3,7 @@ description: go_router_builder examples publish_to: none environment: - sdk: ^3.7.0 + sdk: ^3.8.0 dependencies: collection: ^1.15.0 diff --git a/packages/go_router_builder/lib/src/route_config.dart b/packages/go_router_builder/lib/src/route_config.dart index 3f53838891a..5dae9473a2d 100644 --- a/packages/go_router_builder/lib/src/route_config.dart +++ b/packages/go_router_builder/lib/src/route_config.dart @@ -346,22 +346,22 @@ mixin _GoRouteMixin on RouteBaseConfig { return buffer.toString(); } - late final List _ctorParams = - _ctor.formalParameters.where((FormalParameterElement element) { + late final List _ctorParams = _ctor.formalParameters + .where((FormalParameterElement element) { if (_pathParams.contains(element.displayName)) { return true; } return false; - }).toList(); + }) + .toList(); - late final List _ctorQueryParams = - _ctor.formalParameters - .where( - (FormalParameterElement element) => - !_pathParams.contains(element.displayName) && - !element.isExtraField, - ) - .toList(); + late final List _ctorQueryParams = _ctor + .formalParameters + .where( + (FormalParameterElement element) => + !_pathParams.contains(element.displayName) && !element.isExtraField, + ) + .toList(); ConstructorElement2 get _ctor { final ConstructorElement2? ctor = routeDataClass.unnamedConstructor2; @@ -800,44 +800,42 @@ abstract class RouteBaseConfig { InterfaceElement2 classElement, { required String parameterName, }) { - final String? fieldDisplayName = - classElement.fields2 - .where((FieldElement2 element) { - if (!element.isStatic || element.displayName != parameterName) { - return false; - } - if (parameterName.toLowerCase().contains( - RegExp('navigatorKey | observers'), - )) { - final DartType type = element.type; - if (type is! ParameterizedType) { - return false; - } - final List typeArguments = type.typeArguments; - if (typeArguments.length != 1) { - return false; - } - final DartType typeArgument = typeArguments.single; - if (withoutNullability(typeArgument.getDisplayString()) != - 'NavigatorState') { - return false; - } - } - return true; - }) - .map((FieldElement2 e) => e.displayName) - .firstOrNull; + final String? fieldDisplayName = classElement.fields2 + .where((FieldElement2 element) { + if (!element.isStatic || element.displayName != parameterName) { + return false; + } + if (parameterName.toLowerCase().contains( + RegExp('navigatorKey | observers'), + )) { + final DartType type = element.type; + if (type is! ParameterizedType) { + return false; + } + final List typeArguments = type.typeArguments; + if (typeArguments.length != 1) { + return false; + } + final DartType typeArgument = typeArguments.single; + if (withoutNullability(typeArgument.getDisplayString()) != + 'NavigatorState') { + return false; + } + } + return true; + }) + .map((FieldElement2 e) => e.displayName) + .firstOrNull; if (fieldDisplayName != null) { return '${classElement.displayName}.$fieldDisplayName'; } - final String? methodDisplayName = - classElement.methods2 - .where((MethodElement2 element) { - return element.isStatic && element.displayName == parameterName; - }) - .map((MethodElement2 e) => e.displayName) - .firstOrNull; + final String? methodDisplayName = classElement.methods2 + .where((MethodElement2 element) { + return element.isStatic && element.displayName == parameterName; + }) + .map((MethodElement2 e) => e.displayName) + .firstOrNull; if (methodDisplayName != null) { return '${classElement.displayName}.$methodDisplayName'; @@ -883,7 +881,8 @@ abstract class RouteBaseConfig { r'$' + _className.substring(0, 1).toLowerCase() + _className.substring(1); /// Returns the `GoRoute` code for the annotated class. - String _rootDefinition() => ''' + String _rootDefinition() => + ''' RouteBase get $_routeGetterName => ${_invokesRouteConstructor()}; '''; @@ -894,10 +893,9 @@ RouteBase get $_routeGetterName => ${_invokesRouteConstructor()}; String get _extensionName => '\$${_className}Extension'; String _invokesRouteConstructor() { - final String routesBit = - _children.isEmpty - ? '' - : ''' + final String routesBit = _children.isEmpty + ? '' + : ''' ${_generateChildrenGetterName(routeDataClassName)}: [${_children.map((RouteBaseConfig e) => '${e._invokesRouteConstructor()},').join()}], '''; @@ -910,13 +908,10 @@ $routeDataClassName.$dataConvertionFunctionName( PropertyAccessorElement2? _field(String name) => routeDataClass.getGetter2(name); - List? _fieldMetadata(String name) => - routeDataClass.fields2 - .firstWhereOrNull( - (FieldElement2 element) => element.displayName == name, - ) - ?.metadata2 - .annotations; + List? _fieldMetadata(String name) => routeDataClass.fields2 + .firstWhereOrNull((FieldElement2 element) => element.displayName == name) + ?.metadata2 + .annotations; /// The name of `RouteData` subclass this configuration represents. @protected @@ -968,7 +963,8 @@ const Map helperNames = { iterablesEqualHelperName: _iterableEqualsHelper, }; -const String _convertMapValueHelper = ''' +const String _convertMapValueHelper = + ''' T? $convertMapValueHelperName( String key, Map map, @@ -979,7 +975,8 @@ T? $convertMapValueHelperName( } '''; -const String _boolConverterHelper = ''' +const String _boolConverterHelper = + ''' bool $boolConverterHelperName(String value) { switch (value) { case 'true': @@ -992,13 +989,15 @@ bool $boolConverterHelperName(String value) { } '''; -const String _enumConverterHelper = ''' +const String _enumConverterHelper = + ''' extension on Map { T? $enumExtensionHelperName(String? value) => entries.where((element) => element.value == value).firstOrNull?.key; }'''; -const String _iterableEqualsHelper = ''' +const String _iterableEqualsHelper = + ''' bool $iterablesEqualHelperName(Iterable? iterable1, Iterable? iterable2) { if (identical(iterable1, iterable2)) return true; if (iterable1 == null || iterable2 == null) return false; diff --git a/packages/go_router_builder/lib/src/type_helpers.dart b/packages/go_router_builder/lib/src/type_helpers.dart index 627324d6717..5c4a4d230ad 100644 --- a/packages/go_router_builder/lib/src/type_helpers.dart +++ b/packages/go_router_builder/lib/src/type_helpers.dart @@ -193,8 +193,8 @@ T? getNodeDeclaration(InterfaceElement2 element) { session.getParsedLibraryByElement2(element.library2) as ParsedLibraryResult; final FragmentDeclarationResult? declaration = parsedLibrary - // ignore: experimental_member_use - .getFragmentDeclaration(element.firstFragment); + // ignore: experimental_member_use + .getFragmentDeclaration(element.firstFragment); final AstNode? node = declaration?.node; return node is T ? node : null; @@ -240,8 +240,9 @@ String _stateValueAccess( } late String access; - final String suffix = - !element.type.isNullableType && !element.hasDefaultValue ? '!' : ''; + final String suffix = !element.type.isNullableType && !element.hasDefaultValue + ? '!' + : ''; if (pathParameters.contains(element.displayName)) { access = 'pathParameters[${escapeDartString(element.displayName)}]$suffix'; } else { @@ -738,10 +739,9 @@ class _TypeHelperJson extends _TypeHelperWithHelper { String _helperNameN(DartType paramType, int index) { final String mainType = index == 0 ? 'String' : 'Object?'; - final String mainDecoder = - index == 0 - ? 'jsonDecode(json$index) as Map' - : 'json$index as Map'; + final String mainDecoder = index == 0 + ? 'jsonDecode(json$index) as Map' + : 'json$index as Map'; if (_isNestedTemplate(paramType as InterfaceType)) { return ''' ($mainType json$index) { @@ -836,9 +836,9 @@ abstract class _TypeHelperWithHelper extends _TypeHelper { } final String nullableSuffix = paramType.isNullableType || - (paramType.isEnum && !paramType.isNullableType) - ? '!' - : ''; + (paramType.isEnum && !paramType.isNullableType) + ? '!' + : ''; final String decode = _fieldWithEncoder( 'state.${_stateValueAccess(parameterElement, pathParameters)} ${!parameterElement.isRequired ? " ?? '' " : ''}', diff --git a/packages/go_router_builder/pubspec.yaml b/packages/go_router_builder/pubspec.yaml index b9db11172c0..684ad1ed8a4 100644 --- a/packages/go_router_builder/pubspec.yaml +++ b/packages/go_router_builder/pubspec.yaml @@ -7,8 +7,8 @@ repository: https://github.com/flutter/packages/tree/main/packages/go_router_bui issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+go_router_builder%22 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: analyzer: ">=7.4.0 <9.0.0" diff --git a/packages/go_router_builder/tool/run_tests.dart b/packages/go_router_builder/tool/run_tests.dart index 64df41492ab..40e629e7b37 100644 --- a/packages/go_router_builder/tool/run_tests.dart +++ b/packages/go_router_builder/tool/run_tests.dart @@ -23,12 +23,11 @@ Future main() async { languageVersion: await _packageVersion(), ); final Directory dir = Directory('test_inputs'); - final List testFiles = - dir - .listSync() - .whereType() - .where((File f) => f.path.endsWith('.dart')) - .toList(); + final List testFiles = dir + .listSync() + .whereType() + .where((File f) => f.path.endsWith('.dart')) + .toList(); for (final File file in testFiles) { final String fileName = file.path.split('/').last; final File expectFile = File(p.join('${file.path}.expect')); diff --git a/packages/google_adsense/CHANGELOG.md b/packages/google_adsense/CHANGELOG.md index b524ece4e9e..bbdadf8528f 100644 --- a/packages/google_adsense/CHANGELOG.md +++ b/packages/google_adsense/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 0.1.2 diff --git a/packages/google_adsense/example/integration_test/core_test.dart b/packages/google_adsense/example/integration_test/core_test.dart index fa5b464464a..55404f5526e 100644 --- a/packages/google_adsense/example/integration_test/core_test.dart +++ b/packages/google_adsense/example/integration_test/core_test.dart @@ -90,10 +90,9 @@ void main() async { testWidgets('Skips initialization if script is already present.', ( WidgetTester _, ) async { - final web.HTMLScriptElement script = - web.HTMLScriptElement() - ..id = 'previously-injected' - ..src = testScriptUrl; + final web.HTMLScriptElement script = web.HTMLScriptElement() + ..id = 'previously-injected' + ..src = testScriptUrl; final web.HTMLElement target = web.HTMLDivElement()..appendChild(script); await adSense.initialize(testClient, jsLoaderTarget: target); diff --git a/packages/google_adsense/example/integration_test/experimental_ad_unit_widget_test.dart b/packages/google_adsense/example/integration_test/experimental_ad_unit_widget_test.dart index a59b47a6352..df751abd1e4 100644 --- a/packages/google_adsense/example/integration_test/experimental_ad_unit_widget_test.dart +++ b/packages/google_adsense/example/integration_test/experimental_ad_unit_widget_test.dart @@ -226,7 +226,9 @@ Future pumpAdWidget( CallbackTracker tracker, ) async { await tester.pumpWidget( - MaterialApp(home: Scaffold(body: Center(child: adUnit))), + MaterialApp( + home: Scaffold(body: Center(child: adUnit)), + ), ); final Stopwatch timer = Stopwatch()..start(); diff --git a/packages/google_adsense/example/integration_test/js_interop_mocks/adsbygoogle_js_interop.dart b/packages/google_adsense/example/integration_test/js_interop_mocks/adsbygoogle_js_interop.dart index e3f970b63fb..5a7a0c43e05 100644 --- a/packages/google_adsense/example/integration_test/js_interop_mocks/adsbygoogle_js_interop.dart +++ b/packages/google_adsense/example/integration_test/js_interop_mocks/adsbygoogle_js_interop.dart @@ -19,15 +19,13 @@ external set _adsbygoogle(JSAny? value); /// /// `push` will run in the next tick (`Timer.run`) to ensure async behavior. void mockAdsByGoogle(PushFn push) { - _adsbygoogle = - { - 'push': - (JSAny? params) { - Timer.run(() { - push(params); - }); - }.toJS, - }.jsify(); + _adsbygoogle = { + 'push': (JSAny? params) { + Timer.run(() { + push(params); + }); + }.toJS, + }.jsify(); } /// Sets `adsbygoogle` to null. diff --git a/packages/google_adsense/example/integration_test/js_interop_mocks/adsense_test_js_interop.dart b/packages/google_adsense/example/integration_test/js_interop_mocks/adsense_test_js_interop.dart index 126505aa6b0..7ad3ddeb08d 100644 --- a/packages/google_adsense/example/integration_test/js_interop_mocks/adsense_test_js_interop.dart +++ b/packages/google_adsense/example/integration_test/js_interop_mocks/adsense_test_js_interop.dart @@ -24,8 +24,9 @@ PushFn mockAd({Size size = Size.zero, String adStatus = AdStatus.FILLED}) { /// Returns a function that handles a bunch of ad units at once. Can be used with [mockAdsByGoogle]. PushFn mockAds(List adConfigs) { return (JSAny? _) { - final List foundTargets = - web.document.querySelectorAll('div[id^=adUnit] ins').toList; + final List foundTargets = web.document + .querySelectorAll('div[id^=adUnit] ins') + .toList; for (int i = 0; i < foundTargets.length; i++) { final web.HTMLElement adTarget = foundTargets[i]; @@ -35,11 +36,10 @@ PushFn mockAds(List adConfigs) { final (:Size size, :String adStatus) = adConfigs[i]; - final web.HTMLElement fakeAd = - web.HTMLDivElement() - ..style.width = '${size.width}px' - ..style.height = '${size.height}px' - ..style.background = '#fabada'; + final web.HTMLElement fakeAd = web.HTMLDivElement() + ..style.width = '${size.width}px' + ..style.height = '${size.height}px' + ..style.background = '#fabada'; // AdSense seems to be setting the width/height on the `ins` of the injected ad too. adTarget diff --git a/packages/google_adsense/example/lib/ad_unit_widget.dart b/packages/google_adsense/example/lib/ad_unit_widget.dart index 4987a9037a9..db201cb788f 100644 --- a/packages/google_adsense/example/lib/ad_unit_widget.dart +++ b/packages/google_adsense/example/lib/ad_unit_widget.dart @@ -61,15 +61,15 @@ class _MyHomePageState extends State { constraints: const BoxConstraints(maxWidth: 150), padding: const EdgeInsets.only(bottom: 10), child: - // #docregion adUnit - AdUnitWidget( - configuration: AdUnitConfiguration.displayAdUnit( - // TODO: Replace with your Ad Unit ID - adSlot: '1234567890', - // Remove AdFormat to make ads limited by height - adFormat: AdFormat.AUTO, - ), - ), + // #docregion adUnit + AdUnitWidget( + configuration: AdUnitConfiguration.displayAdUnit( + // TODO: Replace with your Ad Unit ID + adSlot: '1234567890', + // Remove AdFormat to make ads limited by height + adFormat: AdFormat.AUTO, + ), + ), // #enddocregion adUnit ), const Text( diff --git a/packages/google_adsense/example/lib/h5.dart b/packages/google_adsense/example/lib/h5.dart index b880f4485f5..3e2ac65dd21 100644 --- a/packages/google_adsense/example/lib/h5.dart +++ b/packages/google_adsense/example/lib/h5.dart @@ -183,8 +183,9 @@ class _MyHomePageState extends State { style: Theme.of(context).textTheme.displayLarge, ), TextButton.icon( - onPressed: - _h5Ready && !adBreakAvailable ? _requestRewardedAd : null, + onPressed: _h5Ready && !adBreakAvailable + ? _requestRewardedAd + : null, label: const Text('Prepare Reward'), icon: const Icon(Icons.download_rounded), ), diff --git a/packages/google_adsense/example/pubspec.yaml b/packages/google_adsense/example/pubspec.yaml index 6585ef0768e..7b57dcaad35 100644 --- a/packages/google_adsense/example/pubspec.yaml +++ b/packages/google_adsense/example/pubspec.yaml @@ -5,8 +5,8 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev version: 1.0.0+1 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/google_adsense/lib/src/adsense/ad_unit_configuration.dart b/packages/google_adsense/lib/src/adsense/ad_unit_configuration.dart index ca2c836d097..baf3a7aa788 100644 --- a/packages/google_adsense/lib/src/adsense/ad_unit_configuration.dart +++ b/packages/google_adsense/lib/src/adsense/ad_unit_configuration.dart @@ -77,8 +77,8 @@ class AdUnitConfiguration { if (isFullWidthResponsive != null) AdUnitParams.FULL_WIDTH_RESPONSIVE: isFullWidthResponsive.toString(), if (matchedContentUiType != null) - AdUnitParams.MATCHED_CONTENT_UI_TYPE: - matchedContentUiType.toString(), + AdUnitParams.MATCHED_CONTENT_UI_TYPE: matchedContentUiType + .toString(), if (columnsNum != null) AdUnitParams.MATCHED_CONTENT_COLUMNS_NUM: columnsNum.toString(), if (rowsNum != null) diff --git a/packages/google_adsense/lib/src/adsense/ad_unit_widget.dart b/packages/google_adsense/lib/src/adsense/ad_unit_widget.dart index 7473576e854..1f06d326a3e 100644 --- a/packages/google_adsense/lib/src/adsense/ad_unit_widget.dart +++ b/packages/google_adsense/lib/src/adsense/ad_unit_widget.dart @@ -121,10 +121,9 @@ class _AdUnitWidgetWebState extends State }); // Adding ins inside of the adUnit - final web.HTMLDivElement adUnitDiv = - element as web.HTMLDivElement - ..id = 'adUnit${_adUnitCounter++}' - ..append(insElement); + final web.HTMLDivElement adUnitDiv = element as web.HTMLDivElement + ..id = 'adUnit${_adUnitCounter++}' + ..append(insElement); // Using Resize observer to detect element attached to DOM _adSenseResizeObserver.observe(adUnitDiv); @@ -174,15 +173,17 @@ class _AdUnitWidgetWebState extends State } bool _isLoaded(web.HTMLElement target) { - final bool isLoaded = - target.dataset.getProperty(_adStatusKey).isDefinedAndNotNull; + final bool isLoaded = target.dataset + .getProperty(_adStatusKey) + .isDefinedAndNotNull; debugLog('Ad isLoaded: $isLoaded'); return isLoaded; } bool _isFilled(web.HTMLElement target) { - final String? adStatus = - target.dataset.getProperty(_adStatusKey)?.toDart; + final String? adStatus = target.dataset + .getProperty(_adStatusKey) + ?.toDart; debugLog('Ad isFilled? $adStatus'); if (adStatus == AdStatus.FILLED) { return true; diff --git a/packages/google_adsense/lib/src/core/js_interop/js_loader.dart b/packages/google_adsense/lib/src/core/js_interop/js_loader.dart index 430edb366c1..aea3577e0c8 100644 --- a/packages/google_adsense/lib/src/core/js_interop/js_loader.dart +++ b/packages/google_adsense/lib/src/core/js_interop/js_loader.dart @@ -33,10 +33,9 @@ Future loadJsSdk( final String scriptUrl = '$_URL?client=ca-pub-$adClient'; - final web.HTMLScriptElement script = - web.HTMLScriptElement() - ..async = true - ..crossOrigin = 'anonymous'; + final web.HTMLScriptElement script = web.HTMLScriptElement() + ..async = true + ..crossOrigin = 'anonymous'; if (web.window.nullableTrustedTypes != null) { final String trustedTypePolicyName = 'adsense-dart-$adClient'; diff --git a/packages/google_adsense/lib/src/h5/h5_js_interop.dart b/packages/google_adsense/lib/src/h5/h5_js_interop.dart index 3701db037b1..e08ca6369d0 100644 --- a/packages/google_adsense/lib/src/h5/h5_js_interop.dart +++ b/packages/google_adsense/lib/src/h5/h5_js_interop.dart @@ -117,19 +117,18 @@ extension type AdBreakPlacement._(JSObject _) implements JSObject { name: '$_namePrefix${name ?? ''}'.toJS, beforeAd: beforeAd?.toJS, afterAd: afterAd?.toJS, - beforeReward: - beforeReward != null - ? (JSFunction showAdFn) { - beforeReward(() { - // Delay the call to `showAdFn` so tap users don't trigger a click on the - // ad on pointerup. This should leaves enough time for Flutter to settle - // its tap events, before triggering the H5 ad. - Timer(const Duration(milliseconds: 100), () { - showAdFn.callAsFunction(); - }); + beforeReward: beforeReward != null + ? (JSFunction showAdFn) { + beforeReward(() { + // Delay the call to `showAdFn` so tap users don't trigger a click on the + // ad on pointerup. This should leaves enough time for Flutter to settle + // its tap events, before triggering the H5 ad. + Timer(const Duration(milliseconds: 100), () { + showAdFn.callAsFunction(); }); - }.toJS - : null, + }); + }.toJS + : null, adDismissed: adDismissed?.toJS, adViewed: adViewed?.toJS, adBreakDone: adBreakDone?.toJS, diff --git a/packages/google_adsense/pubspec.yaml b/packages/google_adsense/pubspec.yaml index 3b2b65b937b..5457e2b0414 100644 --- a/packages/google_adsense/pubspec.yaml +++ b/packages/google_adsense/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 0.1.2 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/google_fonts/CHANGELOG.md b/packages/google_fonts/CHANGELOG.md index b49a261fe0d..b1192366c6e 100644 --- a/packages/google_fonts/CHANGELOG.md +++ b/packages/google_fonts/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. + ## 6.3.2 - Makes a map keyed on FontWeight non-const for compatibility with proposed changes to the engine's implementation of FontWeight. diff --git a/packages/google_fonts/example/lib/example_font_selection.dart b/packages/google_fonts/example/lib/example_font_selection.dart index f8adaae64ba..5c31dc11439 100644 --- a/packages/google_fonts/example/lib/example_font_selection.dart +++ b/packages/google_fonts/example/lib/example_font_selection.dart @@ -68,13 +68,14 @@ class ExampleFontSelectionState extends State { ); }); }, - dropdownMenuEntries: - GoogleFonts.asMap().keys.map((String font) { - return DropdownMenuEntry( - label: font, - value: font, - ); - }).toList(), + dropdownMenuEntries: GoogleFonts.asMap().keys.map(( + String font, + ) { + return DropdownMenuEntry( + label: font, + value: font, + ); + }).toList(), ), ], ), @@ -82,22 +83,24 @@ class ExampleFontSelectionState extends State { Expanded( child: FutureBuilder>( future: _googleFontsPending, - builder: ( - BuildContext context, - AsyncSnapshot> snapshot, - ) { - if (snapshot.connectionState != ConnectionState.done) { - return const SizedBox(); - } + builder: + ( + BuildContext context, + AsyncSnapshot> snapshot, + ) { + if (snapshot.connectionState != + ConnectionState.done) { + return const SizedBox(); + } - return Text( - _textEditingController.text, - style: GoogleFonts.getFont( - _selectedFont, - fontSize: 50.0, - ), - ); - }, + return Text( + _textEditingController.text, + style: GoogleFonts.getFont( + _selectedFont, + fontSize: 50.0, + ), + ); + }, ), ), ], diff --git a/packages/google_fonts/example/lib/main.dart b/packages/google_fonts/example/lib/main.dart index a89c427c5da..31b2ab85a05 100644 --- a/packages/google_fonts/example/lib/main.dart +++ b/packages/google_fonts/example/lib/main.dart @@ -26,7 +26,10 @@ class MyApp extends StatelessWidget { appBar: AppBar( title: const Text('Google Fonts Demo'), bottom: const TabBar( - tabs: [Tab(text: 'Simple'), Tab(text: 'Select a font')], + tabs: [ + Tab(text: 'Simple'), + Tab(text: 'Select a font'), + ], ), ), body: const TabBarView( diff --git a/packages/google_fonts/example/pubspec.yaml b/packages/google_fonts/example/pubspec.yaml index c2e372294e2..580c0856230 100644 --- a/packages/google_fonts/example/pubspec.yaml +++ b/packages/google_fonts/example/pubspec.yaml @@ -3,7 +3,7 @@ description: A Flutter application showcasing how to use the google_fonts packag publish_to: none environment: - sdk: ^3.7.0 + sdk: ^3.8.0 dependencies: cupertino_icons: ^1.0.0 diff --git a/packages/google_fonts/generator/generator.dart b/packages/google_fonts/generator/generator.dart index d7ff08ef51f..e6b7cba183f 100644 --- a/packages/google_fonts/generator/generator.dart +++ b/packages/google_fonts/generator/generator.dart @@ -112,8 +112,9 @@ Future _tryUrl(http.Client client, Uri url, Font font) async { try { final http.Response fileContents = await client.get(url); final int actualFileLength = fileContents.bodyBytes.length; - final String actualFileHash = - sha256.convert(fileContents.bodyBytes).toString(); + final String actualFileHash = sha256 + .convert(fileContents.bodyBytes) + .toString(); if (font.file.fileSize != actualFileLength || _hashToString(font.file.hash) != actualFileHash) { throw Exception('Font from $url did not match length of or checksum.'); @@ -224,8 +225,9 @@ void _generateDartCode(Directory fontDirectory) { for (final Font variant in item.fonts) { 'variantWeight': variant.weight.start, - 'variantStyle': - variant.italic.start.round() == 1 ? 'italic' : 'normal', + 'variantStyle': variant.italic.start.round() == 1 + ? 'italic' + : 'normal', 'hash': _hashToString(variant.file.hash), 'length': variant.file.fileSize, }, diff --git a/packages/google_fonts/lib/src/google_fonts_base.dart b/packages/google_fonts/lib/src/google_fonts_base.dart index 583ff9011ae..14744275195 100755 --- a/packages/google_fonts/lib/src/google_fonts_base.dart +++ b/packages/google_fonts/lib/src/google_fonts_base.dart @@ -129,8 +129,8 @@ TextStyle googleFontsTextStyle({ /// the [fontUrl] and stored on device. In all cases, the returned future /// completes once the font is loaded into the [FontLoader]. Future loadFontIfNecessary(GoogleFontsDescriptor descriptor) async { - final String familyWithVariantString = - descriptor.familyWithVariant.toString(); + final String familyWithVariantString = descriptor.familyWithVariant + .toString(); final String fontName = descriptor.familyWithVariant.toApiFilenamePrefix(); final String fileHash = descriptor.file.expectedFileHash; // If this font has already already loaded or is loading, then there is no diff --git a/packages/google_fonts/lib/src/google_fonts_variant.dart b/packages/google_fonts/lib/src/google_fonts_variant.dart index 347887ff8ad..a5081f3c93d 100644 --- a/packages/google_fonts/lib/src/google_fonts_variant.dart +++ b/packages/google_fonts/lib/src/google_fonts_variant.dart @@ -48,8 +48,9 @@ class GoogleFontsVariant { variantString == _italic ? 3 : (int.parse(variantString.replaceAll(_italic, '')) ~/ 100) - 1], - fontStyle = - variantString.contains(_italic) ? FontStyle.italic : FontStyle.normal; + fontStyle = variantString.contains(_italic) + ? FontStyle.italic + : FontStyle.normal; final FontWeight fontWeight; final FontStyle fontStyle; @@ -133,8 +134,9 @@ class GoogleFontsVariant { /// See [GoogleFontsVariant.toString] for the inverse function. @override String toString() { - final Object fontWeightString = - fontWeight.index == 3 ? '' : (fontWeight.index + 1) * 100; + final Object fontWeightString = fontWeight.index == 3 + ? '' + : (fontWeight.index + 1) * 100; final String fontStyleString = fontStyle .toString() .replaceAll('FontStyle.', '') diff --git a/packages/google_fonts/pubspec.yaml b/packages/google_fonts/pubspec.yaml index 3a81ffc7a7c..ac3de14c5ee 100644 --- a/packages/google_fonts/pubspec.yaml +++ b/packages/google_fonts/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 6.3.2 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: crypto: ^3.0.0 diff --git a/packages/google_fonts/test/google_fonts_text_style_test.dart b/packages/google_fonts/test/google_fonts_text_style_test.dart index ee756e471d8..bc705d8a8f4 100644 --- a/packages/google_fonts/test/google_fonts_text_style_test.dart +++ b/packages/google_fonts/test/google_fonts_text_style_test.dart @@ -46,10 +46,9 @@ final GoogleFontsFile _fakeResponseFile = GoogleFontsFile( final Map fakeFonts = { const GoogleFontsVariant( - fontWeight: FontWeight.w400, - fontStyle: FontStyle.normal, - ): - _fakeResponseFile, + fontWeight: FontWeight.w400, + fontStyle: FontStyle.normal, + ): _fakeResponseFile, }; void main() { diff --git a/packages/google_identity_services_web/CHANGELOG.md b/packages/google_identity_services_web/CHANGELOG.md index 0ab3ba62c3e..ad78ba8ef01 100644 --- a/packages/google_identity_services_web/CHANGELOG.md +++ b/packages/google_identity_services_web/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 0.3.3+1 diff --git a/packages/google_identity_services_web/example/integration_test/utils.dart b/packages/google_identity_services_web/example/integration_test/utils.dart index c199e5a9d9f..dfab149f73c 100644 --- a/packages/google_identity_services_web/example/integration_test/utils.dart +++ b/packages/google_identity_services_web/example/integration_test/utils.dart @@ -30,10 +30,9 @@ ExpectConfigValueFn createExpectConfigValue(JSObject config) { } else if (matcher is List) { final List old = matcher; matcher = isA().having( - (JSAny? p0) => - (p0 as JSArray?)?.toDart - .map((JSAny? e) => e.dartify()) - .toList(), + (JSAny? p0) => (p0 as JSArray?)?.toDart + .map((JSAny? e) => e.dartify()) + .toList(), 'Array with matching values', old, ); diff --git a/packages/google_identity_services_web/example/pubspec.yaml b/packages/google_identity_services_web/example/pubspec.yaml index a24849fcfa3..1d1d4d36cf6 100644 --- a/packages/google_identity_services_web/example/pubspec.yaml +++ b/packages/google_identity_services_web/example/pubspec.yaml @@ -3,8 +3,8 @@ description: An example for the google_identity_services_web package, OneTap. publish_to: 'none' environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/google_identity_services_web/lib/src/js_interop/google_accounts_id.dart b/packages/google_identity_services_web/lib/src/js_interop/google_accounts_id.dart index 8e11a2ae8af..984ca10bfec 100644 --- a/packages/google_identity_services_web/lib/src/js_interop/google_accounts_id.dart +++ b/packages/google_identity_services_web/lib/src/js_interop/google_accounts_id.dart @@ -310,8 +310,10 @@ extension type IdConfiguration._(JSObject _) implements JSObject { context: context?.toString().toJS, state_cookie_domain: state_cookie_domain?.toJS, ux_mode: ux_mode?.toString().toJS, - allowed_parent_origin: - allowed_parent_origin?.map((String s) => s.toJS).toList().toJS, + allowed_parent_origin: allowed_parent_origin + ?.map((String s) => s.toJS) + .toList() + .toJS, intermediate_iframe_close_callback: intermediate_iframe_close_callback?.toJS, itp_support: itp_support?.toJS, diff --git a/packages/google_identity_services_web/lib/src/js_loader.dart b/packages/google_identity_services_web/lib/src/js_loader.dart index 7cc5990409c..e1712ebd7db 100644 --- a/packages/google_identity_services_web/lib/src/js_loader.dart +++ b/packages/google_identity_services_web/lib/src/js_loader.dart @@ -55,10 +55,9 @@ Future loadWebSdk({ } } - final web.HTMLScriptElement script = - web.HTMLScriptElement() - ..async = true - ..defer = true; + final web.HTMLScriptElement script = web.HTMLScriptElement() + ..async = true + ..defer = true; if (trustedUrl != null) { script.trustedSrc = trustedUrl; } else { diff --git a/packages/google_identity_services_web/pubspec.yaml b/packages/google_identity_services_web/pubspec.yaml index 911900abeeb..7bbc5347745 100644 --- a/packages/google_identity_services_web/pubspec.yaml +++ b/packages/google_identity_services_web/pubspec.yaml @@ -5,7 +5,7 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 0.3.3+1 environment: - sdk: ^3.7.0 + sdk: ^3.8.0 dependencies: meta: ^1.3.0 diff --git a/packages/google_identity_services_web/test/js_loader_test.dart b/packages/google_identity_services_web/test/js_loader_test.dart index d1ef431bae4..9dc836800c7 100644 --- a/packages/google_identity_services_web/test/js_loader_test.dart +++ b/packages/google_identity_services_web/test/js_loader_test.dart @@ -71,8 +71,8 @@ void main() { test('defaults to a nonce set in other script of the page', () async { const String expectedNonce = 'another-random-nonce'; - final web.HTMLScriptElement otherScript = - web.HTMLScriptElement()..nonce = expectedNonce; + final web.HTMLScriptElement otherScript = web.HTMLScriptElement() + ..nonce = expectedNonce; web.document.head?.appendChild(otherScript); // This test doesn't simulate the callback that completes the future, and @@ -89,8 +89,8 @@ void main() { test('when explicitly set overrides the default', () async { const String expectedNonce = 'third-random-nonce'; - final web.HTMLScriptElement otherScript = - web.HTMLScriptElement()..nonce = 'this-is-the-wrong-nonce'; + final web.HTMLScriptElement otherScript = web.HTMLScriptElement() + ..nonce = 'this-is-the-wrong-nonce'; web.document.head?.appendChild(otherScript); // This test doesn't simulate the callback that completes the future, and @@ -106,8 +106,8 @@ void main() { }); test('when null disables the feature', () async { - final web.HTMLScriptElement otherScript = - web.HTMLScriptElement()..nonce = 'this-is-the-wrong-nonce'; + final web.HTMLScriptElement otherScript = web.HTMLScriptElement() + ..nonce = 'this-is-the-wrong-nonce'; web.document.head?.appendChild(otherScript); // This test doesn't simulate the callback that completes the future, and diff --git a/packages/google_maps_flutter/google_maps_flutter/CHANGELOG.md b/packages/google_maps_flutter/google_maps_flutter/CHANGELOG.md index eb60690a37d..64bc5dc7a8b 100644 --- a/packages/google_maps_flutter/google_maps_flutter/CHANGELOG.md +++ b/packages/google_maps_flutter/google_maps_flutter/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. + ## 2.14.0 * Adds a check that raises a `StateError` diff --git a/packages/google_maps_flutter/google_maps_flutter/example/integration_test/src/maps_controller.dart b/packages/google_maps_flutter/google_maps_flutter/example/integration_test/src/maps_controller.dart index 1930f28cb0f..adaee6429af 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/integration_test/src/maps_controller.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/integration_test/src/maps_controller.dart @@ -152,8 +152,8 @@ void runTests() { ); await tester.pumpAndSettle(const Duration(seconds: 3)); - final LatLngBounds secondVisibleRegion = - await mapController.getVisibleRegion(); + final LatLngBounds secondVisibleRegion = await mapController + .getVisibleRegion(); expect(secondVisibleRegion, isNot(zeroLatLngBounds)); diff --git a/packages/google_maps_flutter/google_maps_flutter/example/integration_test/src/shared.dart b/packages/google_maps_flutter/google_maps_flutter/example/integration_test/src/shared.dart index 8913ca4bb48..627e22b3470 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/integration_test/src/shared.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/integration_test/src/shared.dart @@ -50,7 +50,9 @@ Future pumpMap( Widget wrapMap(GoogleMap map, [Size size = const Size.square(200)]) { return MaterialApp( home: Scaffold( - body: Center(child: SizedBox.fromSize(size: size, child: map)), + body: Center( + child: SizedBox.fromSize(size: size, child: map), + ), ), ); } diff --git a/packages/google_maps_flutter/google_maps_flutter/example/integration_test/src/tiles_inspector.dart b/packages/google_maps_flutter/google_maps_flutter/example/integration_test/src/tiles_inspector.dart index 728f6514691..079ac894192 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/integration_test/src/tiles_inspector.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/integration_test/src/tiles_inspector.dart @@ -62,16 +62,14 @@ void runTests() { final int mapId = await mapIdCompleter.future; - final TileOverlay tileOverlayInfo1 = - (await inspector.getTileOverlayInfo( - tileOverlay1.mapsId, - mapId: mapId, - ))!; - final TileOverlay tileOverlayInfo2 = - (await inspector.getTileOverlayInfo( - tileOverlay2.mapsId, - mapId: mapId, - ))!; + final TileOverlay tileOverlayInfo1 = (await inspector.getTileOverlayInfo( + tileOverlay1.mapsId, + mapId: mapId, + ))!; + final TileOverlay tileOverlayInfo2 = (await inspector.getTileOverlayInfo( + tileOverlay2.mapsId, + mapId: mapId, + ))!; expect(tileOverlayInfo1.visible, isTrue); expect(tileOverlayInfo1.fadeIn, isTrue); @@ -147,11 +145,10 @@ void runTests() { await tester.pumpAndSettle(const Duration(seconds: 3)); - final TileOverlay tileOverlayInfo1 = - (await inspector.getTileOverlayInfo( - tileOverlay1.mapsId, - mapId: mapId, - ))!; + final TileOverlay tileOverlayInfo1 = (await inspector.getTileOverlayInfo( + tileOverlay1.mapsId, + mapId: mapId, + ))!; final TileOverlay? tileOverlayInfo2 = await inspector.getTileOverlayInfo( tileOverlay2.mapsId, mapId: mapId, @@ -357,10 +354,14 @@ void runTests() { GoogleMapsInspectorPlatform.instance!; if (inspector.supportsGettingHeatmapInfo()) { - final Heatmap heatmapInfo1 = - (await inspector.getHeatmapInfo(heatmap1.mapsId, mapId: mapId))!; - final Heatmap heatmapInfo2 = - (await inspector.getHeatmapInfo(heatmap2.mapsId, mapId: mapId))!; + final Heatmap heatmapInfo1 = (await inspector.getHeatmapInfo( + heatmap1.mapsId, + mapId: mapId, + ))!; + final Heatmap heatmapInfo2 = (await inspector.getHeatmapInfo( + heatmap2.mapsId, + mapId: mapId, + ))!; expectHeatmapEquals(heatmap1, heatmapInfo1); expectHeatmapEquals(heatmap2, heatmapInfo2); @@ -418,8 +419,10 @@ void runTests() { await tester.pumpAndSettle(const Duration(seconds: 3)); if (inspector.supportsGettingHeatmapInfo()) { - final Heatmap heatmapInfo1 = - (await inspector.getHeatmapInfo(heatmap1.mapsId, mapId: mapId))!; + final Heatmap heatmapInfo1 = (await inspector.getHeatmapInfo( + heatmap1.mapsId, + mapId: mapId, + ))!; expectHeatmapEquals(heatmap1New, heatmapInfo1); } @@ -601,16 +604,10 @@ void runTests() { GoogleMapsInspectorPlatform.instance!; if (inspector.supportsGettingGroundOverlayInfo()) { - final GroundOverlay groundOverlayBoundsInfo1 = - (await inspector.getGroundOverlayInfo( - groundOverlayBounds1.mapsId, - mapId: mapId, - ))!; - final GroundOverlay groundOverlayBoundsInfo2 = - (await inspector.getGroundOverlayInfo( - groundOverlayBounds2.mapsId, - mapId: mapId, - ))!; + final GroundOverlay groundOverlayBoundsInfo1 = (await inspector + .getGroundOverlayInfo(groundOverlayBounds1.mapsId, mapId: mapId))!; + final GroundOverlay groundOverlayBoundsInfo2 = (await inspector + .getGroundOverlayInfo(groundOverlayBounds2.mapsId, mapId: mapId))!; expectGroundOverlayEquals( groundOverlayBounds1, @@ -623,8 +620,8 @@ void runTests() { // Web does not support position-based ground overlays. if (!isWeb) { - final GroundOverlay groundOverlayPositionInfo1 = - (await inspector.getGroundOverlayInfo( + final GroundOverlay groundOverlayPositionInfo1 = (await inspector + .getGroundOverlayInfo( groundOverlayPosition1.mapsId, mapId: mapId, ))!; @@ -704,11 +701,8 @@ void runTests() { await tester.pumpAndSettle(const Duration(seconds: 3)); if (inspector.supportsGettingGroundOverlayInfo()) { - final GroundOverlay groundOverlayBounds1Info = - (await inspector.getGroundOverlayInfo( - groundOverlayBounds1.mapsId, - mapId: mapId, - ))!; + final GroundOverlay groundOverlayBounds1Info = (await inspector + .getGroundOverlayInfo(groundOverlayBounds1.mapsId, mapId: mapId))!; expectGroundOverlayEquals( groundOverlayBounds1New, @@ -717,8 +711,8 @@ void runTests() { // Web does not support position-based ground overlays. if (!isWeb) { - final GroundOverlay groundOverlayPosition1Info = - (await inspector.getGroundOverlayInfo( + final GroundOverlay groundOverlayPosition1Info = (await inspector + .getGroundOverlayInfo( groundOverlayPosition1.mapsId, mapId: mapId, ))!; diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/animate_camera.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/animate_camera.dart index 422fb050327..19687ea1d68 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/animate_camera.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/animate_camera.dart @@ -40,10 +40,9 @@ class AnimateCameraState extends State { void _toggleAnimationDuration() { setState(() { - _cameraUpdateAnimationDuration = - _cameraUpdateAnimationDuration != null - ? null - : const Duration(seconds: _durationSeconds); + _cameraUpdateAnimationDuration = _cameraUpdateAnimationDuration != null + ? null + : const Duration(seconds: _durationSeconds); }); } @@ -193,12 +192,11 @@ class AnimateCameraState extends State { const SizedBox(width: 5), Switch( value: _cameraUpdateAnimationDuration != null, - onChanged: - kIsWeb - ? null - : (bool value) { - _toggleAnimationDuration(); - }, + onChanged: kIsWeb + ? null + : (bool value) { + _toggleAnimationDuration(); + }, ), ], ), diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/clustering.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/clustering.dart index a021ac54132..0a22df4fdaa 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/clustering.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/clustering.dart @@ -125,10 +125,9 @@ class ClusteringBodyState extends State { final ClusterManager clusterManager = ClusterManager( clusterManagerId: clusterManagerId, - onClusterTap: - (Cluster cluster) => setState(() { - lastCluster = cluster; - }), + onClusterTap: (Cluster cluster) => setState(() { + lastCluster = cluster; + }), ); setState(() { @@ -197,10 +196,9 @@ class ClusteringBodyState extends State { final Marker marker = markers[markerId]!; final double current = marker.alpha; markers[markerId] = marker.copyWith( - alphaParam: - current == _fullyVisibleAlpha - ? _halfVisibleAlpha - : _fullyVisibleAlpha, + alphaParam: current == _fullyVisibleAlpha + ? _halfVisibleAlpha + : _fullyVisibleAlpha, ); } setState(() {}); @@ -230,19 +228,16 @@ class ClusteringBodyState extends State { mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ TextButton( - onPressed: - clusterManagers.length >= _clusterManagerMaxCount - ? null - : () => _addClusterManager(), + onPressed: clusterManagers.length >= _clusterManagerMaxCount + ? null + : () => _addClusterManager(), child: const Text('Add cluster manager'), ), TextButton( - onPressed: - clusterManagers.isEmpty - ? null - : () => _removeClusterManager( - clusterManagers.values.last, - ), + onPressed: clusterManagers.isEmpty + ? null + : () => + _removeClusterManager(clusterManagers.values.last), child: const Text('Remove cluster manager'), ), ], @@ -263,20 +258,20 @@ class ClusteringBodyState extends State { alignment: WrapAlignment.spaceEvenly, children: [ TextButton( - onPressed: - selectedId == null - ? null - : () { - _remove(selectedId); - setState(() { - selectedMarker = null; - }); - }, + onPressed: selectedId == null + ? null + : () { + _remove(selectedId); + setState(() { + selectedMarker = null; + }); + }, child: const Text('Remove selected marker'), ), TextButton( - onPressed: - markers.isEmpty ? null : () => _changeMarkersAlpha(), + onPressed: markers.isEmpty + ? null + : () => _changeMarkersAlpha(), child: const Text('Change all markers alpha'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/ground_overlay.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/ground_overlay.dart index 69c6f654a35..2b5772af8b8 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/ground_overlay.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/ground_overlay.dart @@ -136,8 +136,9 @@ class GroundOverlayBodyState extends State { assert(_groundOverlay != null); setState(() { _groundOverlay = _groundOverlay!.copyWith( - bearingParam: - _groundOverlay!.bearing >= 350 ? 0 : _groundOverlay!.bearing + 10, + bearingParam: _groundOverlay!.bearing >= 350 + ? 0 + : _groundOverlay!.bearing + 10, ); }); } @@ -145,8 +146,9 @@ class GroundOverlayBodyState extends State { void _changeTransparency() { assert(_groundOverlay != null); setState(() { - final double transparency = - _groundOverlay!.transparency == 0.0 ? 0.5 : 0.0; + final double transparency = _groundOverlay!.transparency == 0.0 + ? 0.5 + : 0.0; _groundOverlay = _groundOverlay!.copyWith( transparencyParam: transparency, ); @@ -157,10 +159,9 @@ class GroundOverlayBodyState extends State { assert(_groundOverlay != null); assert(_placingType == _GroundOverlayPlacing.position); setState(() { - _dimensions = - _dimensions == const Offset(1000, 1000) - ? const Offset(1500, 500) - : const Offset(1000, 1000); + _dimensions = _dimensions == const Offset(1000, 1000) + ? const Offset(1500, 500) + : const Offset(1000, 1000); }); // Re-add the ground overlay to apply the new position, as the position @@ -172,10 +173,9 @@ class GroundOverlayBodyState extends State { assert(_groundOverlay != null); assert(_placingType == _GroundOverlayPlacing.position); setState(() { - _currentGroundOverlayPos = - _currentGroundOverlayPos == _groundOverlayPos1 - ? _groundOverlayPos2 - : _groundOverlayPos1; + _currentGroundOverlayPos = _currentGroundOverlayPos == _groundOverlayPos1 + ? _groundOverlayPos2 + : _groundOverlayPos1; }); // Re-add the ground overlay to apply the new position, as the position @@ -189,8 +189,8 @@ class GroundOverlayBodyState extends State { setState(() { _currentGroundOverlayBounds = _currentGroundOverlayBounds == _groundOverlayBounds1 - ? _groundOverlayBounds2 - : _groundOverlayBounds1; + ? _groundOverlayBounds2 + : _groundOverlayBounds1; }); // Re-add the ground overlay to apply the new bounds as the bounds cannot be @@ -218,10 +218,9 @@ class GroundOverlayBodyState extends State { Future _changeType() async { setState(() { - _placingType = - _placingType == _GroundOverlayPlacing.position - ? _GroundOverlayPlacing.bounds - : _GroundOverlayPlacing.position; + _placingType = _placingType == _GroundOverlayPlacing.position + ? _GroundOverlayPlacing.bounds + : _GroundOverlayPlacing.position; }); // Re-add the ground overlay to change the positioning type. @@ -231,10 +230,9 @@ class GroundOverlayBodyState extends State { Future _changeAnchor() async { assert(_groundOverlay != null); setState(() { - _anchor = - _groundOverlay!.anchor == const Offset(0.5, 0.5) - ? const Offset(1.0, 1.0) - : const Offset(0.5, 0.5); + _anchor = _groundOverlay!.anchor == const Offset(0.5, 0.5) + ? const Offset(1.0, 1.0) + : const Offset(0.5, 0.5); }); // Re-add the ground overlay to apply the new anchor as the anchor cannot be @@ -279,8 +277,9 @@ class GroundOverlayBodyState extends State { alignment: WrapAlignment.spaceEvenly, children: [ TextButton( - onPressed: - _groundOverlay == null ? null : () => _changeTransparency(), + onPressed: _groundOverlay == null + ? null + : () => _changeTransparency(), child: const Text('change transparency'), ), if (!kIsWeb) @@ -294,14 +293,16 @@ class GroundOverlayBodyState extends State { ), if (!kIsWeb) TextButton( - onPressed: - _groundOverlay == null ? null : () => _changeZIndex(), + onPressed: _groundOverlay == null + ? null + : () => _changeZIndex(), child: const Text('change zIndex'), ), if (!kIsWeb) TextButton( - onPressed: - _groundOverlay == null ? null : () => _changeAnchor(), + onPressed: _groundOverlay == null + ? null + : () => _changeAnchor(), child: const Text('change anchor'), ), if (!kIsWeb) @@ -317,26 +318,26 @@ class GroundOverlayBodyState extends State { TextButton( onPressed: _placingType != _GroundOverlayPlacing.position || - _groundOverlay == null - ? null - : () => _changePosition(), + _groundOverlay == null + ? null + : () => _changePosition(), child: const Text('change position'), ), if (defaultTargetPlatform == TargetPlatform.android) TextButton( onPressed: _placingType != _GroundOverlayPlacing.position || - _groundOverlay == null - ? null - : () => _changeDimensions(), + _groundOverlay == null + ? null + : () => _changeDimensions(), child: const Text('change dimensions'), ), TextButton( onPressed: _placingType != _GroundOverlayPlacing.bounds || - _groundOverlay == null - ? null - : () => _changeBounds(), + _groundOverlay == null + ? null + : () => _changeBounds(), child: const Text('change bounds'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/heatmap.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/heatmap.dart index b8f63fccd98..ceb776fab5b 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/heatmap.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/heatmap.dart @@ -127,13 +127,15 @@ class HeatmapBodyState extends State { Column( children: [ TextButton( - onPressed: - disabledPoints.isNotEmpty ? _addPoint : null, + onPressed: disabledPoints.isNotEmpty + ? _addPoint + : null, child: const Text('Add point'), ), TextButton( - onPressed: - enabledPoints.isNotEmpty ? _removePoint : null, + onPressed: enabledPoints.isNotEmpty + ? _removePoint + : null, child: const Text('Remove point'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/main.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/main.dart index 3acbcb51b91..8b33fc9ddaf 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/main.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/main.dart @@ -59,9 +59,10 @@ class MapsDemo extends StatelessWidget { void _pushPage(BuildContext context, GoogleMapExampleAppPage page) { Navigator.of(context).push( MaterialPageRoute( - builder: - (_) => - Scaffold(appBar: AppBar(title: Text(page.title)), body: page), + builder: (_) => Scaffold( + appBar: AppBar(title: Text(page.title)), + body: page, + ), ), ); } @@ -72,12 +73,11 @@ class MapsDemo extends StatelessWidget { appBar: AppBar(title: const Text('GoogleMaps examples')), body: ListView.builder( itemCount: _allPages.length, - itemBuilder: - (_, int index) => ListTile( - leading: _allPages[index].leading, - title: Text(_allPages[index].title), - onTap: () => _pushPage(context, _allPages[index]), - ), + itemBuilder: (_, int index) => ListTile( + leading: _allPages[index].leading, + title: Text(_allPages[index].title), + onTap: () => _pushPage(context, _allPages[index]), + ), ), ); } diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/map_ui.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/map_ui.dart index fc79a76949d..3afa4a596f4 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/map_ui.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/map_ui.dart @@ -89,45 +89,43 @@ class MapUiBodyState extends State { Widget _webCameraControlPositionToggler() { return TextButton( - onPressed: - () => showDialog( - context: context, - builder: (BuildContext context) { - return AlertDialog( - title: const Text('Web camera control position'), - content: Column( - mainAxisSize: MainAxisSize.min, - children: [ - DropdownButton( - hint: const Text('Web camera control position'), - value: _webCameraControlPosition, - items: - WebCameraControlPosition.values - .map( - (WebCameraControlPosition e) => - DropdownMenuItem( - value: e, - child: Text(e.name), - ), - ) - .toList(), - onChanged: (WebCameraControlPosition? value) { - setState(() { - _webCameraControlPosition = value; - }); - }, - ), - TextButton( - onPressed: () { - Navigator.pop(context); - }, - child: const Text('Ok'), - ), - ], + onPressed: () => showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: const Text('Web camera control position'), + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + DropdownButton( + hint: const Text('Web camera control position'), + value: _webCameraControlPosition, + items: WebCameraControlPosition.values + .map( + (WebCameraControlPosition e) => + DropdownMenuItem( + value: e, + child: Text(e.name), + ), + ) + .toList(), + onChanged: (WebCameraControlPosition? value) { + setState(() { + _webCameraControlPosition = value; + }); + }, ), - ); - }, - ), + TextButton( + onPressed: () { + Navigator.pop(context); + }, + child: const Text('Ok'), + ), + ], + ), + ); + }, + ), child: const Text('change web camera control position'), ); } @@ -163,10 +161,9 @@ class MapUiBodyState extends State { ), onPressed: () { setState(() { - _cameraTargetBounds = - _cameraTargetBounds.bounds == null - ? CameraTargetBounds(sydneyBounds) - : CameraTargetBounds.unbounded; + _cameraTargetBounds = _cameraTargetBounds.bounds == null + ? CameraTargetBounds(sydneyBounds) + : CameraTargetBounds.unbounded; }); }, ); @@ -179,10 +176,9 @@ class MapUiBodyState extends State { ), onPressed: () { setState(() { - _minMaxZoomPreference = - _minMaxZoomPreference.minZoom == null - ? const MinMaxZoomPreference(12.0, 16.0) - : MinMaxZoomPreference.unbounded; + _minMaxZoomPreference = _minMaxZoomPreference.minZoom == null + ? const MinMaxZoomPreference(12.0, 16.0) + : MinMaxZoomPreference.unbounded; }); }, ); @@ -317,8 +313,9 @@ class MapUiBodyState extends State { child: Text('${_nightMode ? 'disable' : 'enable'} night mode'), onPressed: () async { _nightMode = !_nightMode; - final String style = - _nightMode ? await _getFileData('assets/night_mode.json') : ''; + final String style = _nightMode + ? await _getFileData('assets/night_mode.json') + : ''; setState(() { _mapStyle = style; }); diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/marker_icons.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/marker_icons.dart index 05c6343c84e..303adcce686 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/marker_icons.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/marker_icons.dart @@ -111,15 +111,14 @@ class MarkerIconsBodyState extends State { }); } }, - items: - _MarkerSizeOption.values.map(( - _MarkerSizeOption option, - ) { - return DropdownMenuItem<_MarkerSizeOption>( - value: option, - child: Text(_getMarkerSizeOptionName(option)), - ); - }).toList(), + items: _MarkerSizeOption.values.map(( + _MarkerSizeOption option, + ) { + return DropdownMenuItem<_MarkerSizeOption>( + value: option, + child: Text(_getMarkerSizeOptionName(option)), + ); + }).toList(), ), ], ), @@ -252,10 +251,12 @@ class MarkerIconsBodyState extends State { Future _updateMarkerAssetImage(BuildContext context) async { // Width and height are used only for custom size. - final (double? width, double? height) = - _scalingEnabled && _customSizeEnabled - ? _getCurrentMarkerSize() - : (null, null); + final ( + double? width, + double? height, + ) = _scalingEnabled && _customSizeEnabled + ? _getCurrentMarkerSize() + : (null, null); AssetMapBitmap assetMapBitmap; if (_mipMapsEnabled) { @@ -267,8 +268,9 @@ class MarkerIconsBodyState extends State { 'assets/red_square.png', width: width, height: height, - bitmapScaling: - _scalingEnabled ? MapBitmapScaling.auto : MapBitmapScaling.none, + bitmapScaling: _scalingEnabled + ? MapBitmapScaling.auto + : MapBitmapScaling.none, ); } else { // Uses hardcoded asset path @@ -278,8 +280,9 @@ class MarkerIconsBodyState extends State { 'assets/red_square.png', width: width, height: height, - bitmapScaling: - _scalingEnabled ? MapBitmapScaling.auto : MapBitmapScaling.none, + bitmapScaling: _scalingEnabled + ? MapBitmapScaling.auto + : MapBitmapScaling.none, ); } @@ -303,18 +306,21 @@ class MarkerIconsBodyState extends State { final ByteData bytes = await createCustomMarkerIconImage(size: canvasSize); // Width and height are used only for custom size. - final (double? width, double? height) = - _scalingEnabled && _customSizeEnabled - ? _getCurrentMarkerSize() - : (null, null); + final ( + double? width, + double? height, + ) = _scalingEnabled && _customSizeEnabled + ? _getCurrentMarkerSize() + : (null, null); final BytesMapBitmap bitmap = BytesMapBitmap( bytes.buffer.asUint8List(), imagePixelRatio: imagePixelRatio, width: width, height: height, - bitmapScaling: - _scalingEnabled ? MapBitmapScaling.auto : MapBitmapScaling.none, + bitmapScaling: _scalingEnabled + ? MapBitmapScaling.auto + : MapBitmapScaling.none, ); _updateBytesBitmap(bitmap); diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/place_circle.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/place_circle.dart index 09738a8d977..44f3d23f28c 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/place_circle.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/place_circle.dart @@ -170,17 +170,15 @@ class PlaceCircleBodyState extends State { children: [ TextButton(onPressed: _add, child: const Text('add')), TextButton( - onPressed: - (selectedId == null) - ? null - : () => _remove(selectedId), + onPressed: (selectedId == null) + ? null + : () => _remove(selectedId), child: const Text('remove'), ), TextButton( - onPressed: - (selectedId == null) - ? null - : () => _toggleVisible(selectedId), + onPressed: (selectedId == null) + ? null + : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), ], @@ -188,24 +186,21 @@ class PlaceCircleBodyState extends State { Column( children: [ TextButton( - onPressed: - (selectedId == null) - ? null - : () => _changeStrokeWidth(selectedId), + onPressed: (selectedId == null) + ? null + : () => _changeStrokeWidth(selectedId), child: const Text('change stroke width'), ), TextButton( - onPressed: - (selectedId == null) - ? null - : () => _changeStrokeColor(selectedId), + onPressed: (selectedId == null) + ? null + : () => _changeStrokeColor(selectedId), child: const Text('change stroke color'), ), TextButton( - onPressed: - (selectedId == null) - ? null - : () => _changeFillColor(selectedId), + onPressed: (selectedId == null) + ? null + : () => _changeFillColor(selectedId), child: const Text('change fill color'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/place_marker.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/place_marker.dart index 4cd03cc1c88..96ff31d0a3a 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/place_marker.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/place_marker.dart @@ -286,8 +286,9 @@ class PlaceMarkerBodyState extends State { children: [ TextButton(onPressed: _add, child: const Text('Add')), TextButton( - onPressed: - selectedId == null ? null : () => _remove(selectedId), + onPressed: selectedId == null + ? null + : () => _remove(selectedId), child: const Text('Remove'), ), ], @@ -296,82 +297,73 @@ class PlaceMarkerBodyState extends State { alignment: WrapAlignment.spaceEvenly, children: [ TextButton( - onPressed: - selectedId == null ? null : () => _changeInfo(selectedId), + onPressed: selectedId == null + ? null + : () => _changeInfo(selectedId), child: const Text('change info'), ), TextButton( - onPressed: - selectedId == null - ? null - : () => _changeInfoAnchor(selectedId), + onPressed: selectedId == null + ? null + : () => _changeInfoAnchor(selectedId), child: const Text('change info anchor'), ), TextButton( - onPressed: - selectedId == null - ? null - : () => _changeAlpha(selectedId), + onPressed: selectedId == null + ? null + : () => _changeAlpha(selectedId), child: const Text('change alpha'), ), TextButton( - onPressed: - selectedId == null - ? null - : () => _changeAnchor(selectedId), + onPressed: selectedId == null + ? null + : () => _changeAnchor(selectedId), child: const Text('change anchor'), ), TextButton( - onPressed: - selectedId == null - ? null - : () => _toggleDraggable(selectedId), + onPressed: selectedId == null + ? null + : () => _toggleDraggable(selectedId), child: const Text('toggle draggable'), ), TextButton( - onPressed: - selectedId == null ? null : () => _toggleFlat(selectedId), + onPressed: selectedId == null + ? null + : () => _toggleFlat(selectedId), child: const Text('toggle flat'), ), TextButton( - onPressed: - selectedId == null - ? null - : () => _changePosition(selectedId), + onPressed: selectedId == null + ? null + : () => _changePosition(selectedId), child: const Text('change position'), ), TextButton( - onPressed: - selectedId == null - ? null - : () => _changeRotation(selectedId), + onPressed: selectedId == null + ? null + : () => _changeRotation(selectedId), child: const Text('change rotation'), ), TextButton( - onPressed: - selectedId == null - ? null - : () => _toggleVisible(selectedId), + onPressed: selectedId == null + ? null + : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), TextButton( - onPressed: - selectedId == null - ? null - : () => _changeZIndex(selectedId), + onPressed: selectedId == null + ? null + : () => _changeZIndex(selectedId), child: const Text('change zIndex'), ), TextButton( - onPressed: - selectedId == null - ? null - : () { - _getMarkerIcon(context).then(( - BitmapDescriptor icon, - ) { - _setMarkerIcon(selectedId, icon); - }); - }, + onPressed: selectedId == null + ? null + : () { + _getMarkerIcon(context).then((BitmapDescriptor icon) { + _setMarkerIcon(selectedId, icon); + }); + }, child: const Text('set marker icon'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/place_polygon.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/place_polygon.dart index f00b1fab979..e8cf201a41e 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/place_polygon.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/place_polygon.dart @@ -193,24 +193,21 @@ class PlacePolygonBodyState extends State { children: [ TextButton(onPressed: _add, child: const Text('add')), TextButton( - onPressed: - (selectedId == null) - ? null - : () => _remove(selectedId), + onPressed: (selectedId == null) + ? null + : () => _remove(selectedId), child: const Text('remove'), ), TextButton( - onPressed: - (selectedId == null) - ? null - : () => _toggleVisible(selectedId), + onPressed: (selectedId == null) + ? null + : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), TextButton( - onPressed: - (selectedId == null) - ? null - : () => _toggleGeodesic(selectedId), + onPressed: (selectedId == null) + ? null + : () => _toggleGeodesic(selectedId), child: const Text('toggle geodesic'), ), ], @@ -218,42 +215,37 @@ class PlacePolygonBodyState extends State { Column( children: [ TextButton( - onPressed: - (selectedId == null) - ? null - : (polygons[selectedId]!.holes.isNotEmpty - ? null - : () => _addHoles(selectedId)), + onPressed: (selectedId == null) + ? null + : (polygons[selectedId]!.holes.isNotEmpty + ? null + : () => _addHoles(selectedId)), child: const Text('add holes'), ), TextButton( - onPressed: - (selectedId == null) - ? null - : (polygons[selectedId]!.holes.isEmpty - ? null - : () => _removeHoles(selectedId)), + onPressed: (selectedId == null) + ? null + : (polygons[selectedId]!.holes.isEmpty + ? null + : () => _removeHoles(selectedId)), child: const Text('remove holes'), ), TextButton( - onPressed: - (selectedId == null) - ? null - : () => _changeWidth(selectedId), + onPressed: (selectedId == null) + ? null + : () => _changeWidth(selectedId), child: const Text('change stroke width'), ), TextButton( - onPressed: - (selectedId == null) - ? null - : () => _changeStrokeColor(selectedId), + onPressed: (selectedId == null) + ? null + : () => _changeStrokeColor(selectedId), child: const Text('change stroke color'), ), TextButton( - onPressed: - (selectedId == null) - ? null - : () => _changeFillColor(selectedId), + onPressed: (selectedId == null) + ? null + : () => _changeFillColor(selectedId), child: const Text('change fill color'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/place_polyline.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/place_polyline.dart index 330f1ab3be6..083c575cc90 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/place_polyline.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/place_polyline.dart @@ -236,24 +236,21 @@ class PlacePolylineBodyState extends State { children: [ TextButton(onPressed: _add, child: const Text('add')), TextButton( - onPressed: - (selectedId == null) - ? null - : () => _remove(selectedId), + onPressed: (selectedId == null) + ? null + : () => _remove(selectedId), child: const Text('remove'), ), TextButton( - onPressed: - (selectedId == null) - ? null - : () => _toggleVisible(selectedId), + onPressed: (selectedId == null) + ? null + : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), TextButton( - onPressed: - (selectedId == null) - ? null - : () => _toggleGeodesic(selectedId), + onPressed: (selectedId == null) + ? null + : () => _toggleGeodesic(selectedId), child: const Text('toggle geodesic'), ), ], @@ -261,45 +258,39 @@ class PlacePolylineBodyState extends State { Column( children: [ TextButton( - onPressed: - (selectedId == null) - ? null - : () => _changeWidth(selectedId), + onPressed: (selectedId == null) + ? null + : () => _changeWidth(selectedId), child: const Text('change width'), ), TextButton( - onPressed: - (selectedId == null) - ? null - : () => _changeColor(selectedId), + onPressed: (selectedId == null) + ? null + : () => _changeColor(selectedId), child: const Text('change color'), ), TextButton( - onPressed: - isIOS || (selectedId == null) - ? null - : () => _changeStartCap(selectedId), + onPressed: isIOS || (selectedId == null) + ? null + : () => _changeStartCap(selectedId), child: const Text('change start cap [Android only]'), ), TextButton( - onPressed: - isIOS || (selectedId == null) - ? null - : () => _changeEndCap(selectedId), + onPressed: isIOS || (selectedId == null) + ? null + : () => _changeEndCap(selectedId), child: const Text('change end cap [Android only]'), ), TextButton( - onPressed: - isIOS || (selectedId == null) - ? null - : () => _changeJointType(selectedId), + onPressed: isIOS || (selectedId == null) + ? null + : () => _changeJointType(selectedId), child: const Text('change joint type [Android only]'), ), TextButton( - onPressed: - (selectedId == null) - ? null - : () => _changePattern(selectedId), + onPressed: (selectedId == null) + ? null + : () => _changePattern(selectedId), child: const Text('change pattern'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/scrolling_map.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/scrolling_map.dart index 091555efd0e..fa4fa8bd816 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/scrolling_map.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/scrolling_map.dart @@ -49,7 +49,7 @@ class ScrollingMapBody extends StatelessWidget { zoom: 11.0, ), gestureRecognizers: // - >{ + >{ Factory( () => EagerGestureRecognizer(), ), diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/snapshot.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/snapshot.dart index 646d7eca7ae..f94a7d280ef 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/snapshot.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/snapshot.dart @@ -56,8 +56,8 @@ class _SnapshotBodyState extends State<_SnapshotBody> { TextButton( child: const Text('Take a snapshot'), onPressed: () async { - final Uint8List? imageBytes = - await _mapController?.takeSnapshot(); + final Uint8List? imageBytes = await _mapController + ?.takeSnapshot(); setState(() { _imageBytes = imageBytes; }); diff --git a/packages/google_maps_flutter/google_maps_flutter/example/pubspec.yaml b/packages/google_maps_flutter/google_maps_flutter/example/pubspec.yaml index d8fcc8a840c..0e002e4f535 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/pubspec.yaml +++ b/packages/google_maps_flutter/google_maps_flutter/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the google_maps_flutter plugin. publish_to: none environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: cupertino_icons: ^1.0.5 diff --git a/packages/google_maps_flutter/google_maps_flutter/pubspec.yaml b/packages/google_maps_flutter/google_maps_flutter/pubspec.yaml index a271bd524b4..7f16bf9fb63 100644 --- a/packages/google_maps_flutter/google_maps_flutter/pubspec.yaml +++ b/packages/google_maps_flutter/google_maps_flutter/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.14.0 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" flutter: plugin: diff --git a/packages/google_maps_flutter/google_maps_flutter/test/fake_google_maps_flutter_platform.dart b/packages/google_maps_flutter/google_maps_flutter/test/fake_google_maps_flutter_platform.dart index 2433f65793a..fe0439d6c69 100644 --- a/packages/google_maps_flutter/google_maps_flutter/test/fake_google_maps_flutter_platform.dart +++ b/packages/google_maps_flutter/google_maps_flutter/test/fake_google_maps_flutter_platform.dart @@ -135,11 +135,11 @@ class FakeGoogleMapsFlutterPlatform extends GoogleMapsFlutterPlatform { CameraUpdate cameraUpdate, { required int mapId, }) async { - mapInstances[mapId] - ?.animateCameraConfiguration = CameraUpdateWithConfiguration( - cameraUpdate: cameraUpdate, - configuration: null, - ); + mapInstances[mapId]?.animateCameraConfiguration = + CameraUpdateWithConfiguration( + cameraUpdate: cameraUpdate, + configuration: null, + ); await _fakeDelay(); } @@ -149,11 +149,11 @@ class FakeGoogleMapsFlutterPlatform extends GoogleMapsFlutterPlatform { CameraUpdateAnimationConfiguration configuration, { required int mapId, }) async { - mapInstances[mapId] - ?.animateCameraConfiguration = CameraUpdateWithConfiguration( - cameraUpdate: cameraUpdate, - configuration: configuration, - ); + mapInstances[mapId]?.animateCameraConfiguration = + CameraUpdateWithConfiguration( + cameraUpdate: cameraUpdate, + configuration: configuration, + ); await _fakeDelay(); } diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/CHANGELOG.md b/packages/google_maps_flutter/google_maps_flutter_ios/CHANGELOG.md index 8d82f086aeb..f2e21bd481f 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/CHANGELOG.md +++ b/packages/google_maps_flutter/google_maps_flutter_ios/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 2.15.5 diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/ios14/integration_test/google_maps_test.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/ios14/integration_test/google_maps_test.dart index dae1ec41caa..5eb14dbdd0e 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/ios14/integration_test/google_maps_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/ios14/integration_test/google_maps_test.dart @@ -440,8 +440,8 @@ void main() { final ExampleGoogleMapController mapController = await mapControllerCompleter.future; - final LatLngBounds firstVisibleRegion = - await mapController.getVisibleRegion(); + final LatLngBounds firstVisibleRegion = await mapController + .getVisibleRegion(); expect(firstVisibleRegion, isNotNull); expect(firstVisibleRegion.southwest, isNotNull); @@ -480,8 +480,8 @@ void main() { ); await tester.pumpAndSettle(const Duration(seconds: 3)); - final LatLngBounds secondVisibleRegion = - await mapController.getVisibleRegion(); + final LatLngBounds secondVisibleRegion = await mapController + .getVisibleRegion(); expect(secondVisibleRegion, isNotNull); expect(secondVisibleRegion.southwest, isNotNull); @@ -1090,16 +1090,14 @@ void main() { final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; - final TileOverlay tileOverlayInfo1 = - (await inspector.getTileOverlayInfo( - tileOverlay1.mapsId, - mapId: mapId, - ))!; - final TileOverlay tileOverlayInfo2 = - (await inspector.getTileOverlayInfo( - tileOverlay2.mapsId, - mapId: mapId, - ))!; + final TileOverlay tileOverlayInfo1 = (await inspector.getTileOverlayInfo( + tileOverlay1.mapsId, + mapId: mapId, + ))!; + final TileOverlay tileOverlayInfo2 = (await inspector.getTileOverlayInfo( + tileOverlay2.mapsId, + mapId: mapId, + ))!; expect(tileOverlayInfo1.visible, isTrue); expect(tileOverlayInfo1.fadeIn, isTrue); @@ -1177,11 +1175,10 @@ void main() { await tester.pumpAndSettle(const Duration(seconds: 3)); - final TileOverlay tileOverlayInfo1 = - (await inspector.getTileOverlayInfo( - tileOverlay1.mapsId, - mapId: mapId, - ))!; + final TileOverlay tileOverlayInfo1 = (await inspector.getTileOverlayInfo( + tileOverlay1.mapsId, + mapId: mapId, + ))!; final TileOverlay? tileOverlayInfo2 = await inspector.getTileOverlayInfo( tileOverlay2.mapsId, mapId: mapId, @@ -1318,14 +1315,13 @@ void main() { } // Move marker from the first cluster manager to the last. - final MarkerId markerIdToMove = - markers.entries - .firstWhere( - (MapEntry entry) => - entry.value.clusterManagerId == - clusterManagers.first.clusterManagerId, - ) - .key; + final MarkerId markerIdToMove = markers.entries + .firstWhere( + (MapEntry entry) => + entry.value.clusterManagerId == + clusterManagers.first.clusterManagerId, + ) + .key; markers[markerIdToMove] = _copyMarkerWithClusterManagerId( markers[markerIdToMove]!, clusterManagers.last.clusterManagerId, @@ -1564,9 +1560,8 @@ void main() { target: LatLng(10.0, 15.0), ), markers: markers, - onMapCreated: - (ExampleGoogleMapController controller) => - controllerCompleter.complete(controller), + onMapCreated: (ExampleGoogleMapController controller) => + controllerCompleter.complete(controller), ), ), ); @@ -1594,9 +1589,8 @@ void main() { target: LatLng(10.0, 15.0), ), markers: markers, - onMapCreated: - (ExampleGoogleMapController controller) => - controllerCompleter.complete(controller), + onMapCreated: (ExampleGoogleMapController controller) => + controllerCompleter.complete(controller), ), ), ); @@ -1701,18 +1695,12 @@ void main() { GoogleMapsInspectorPlatform.instance!; if (inspector.supportsGettingGroundOverlayInfo()) { - final GroundOverlay groundOverlayBoundsInfo1 = - (await inspector.getGroundOverlayInfo( - groundOverlayBounds1.mapsId, - mapId: mapId, - ))!; - final GroundOverlay groundOverlayBoundsInfo2 = - (await inspector.getGroundOverlayInfo( - groundOverlayBounds2.mapsId, - mapId: mapId, - ))!; - final GroundOverlay groundOverlayPositionInfo1 = - (await inspector.getGroundOverlayInfo( + final GroundOverlay groundOverlayBoundsInfo1 = (await inspector + .getGroundOverlayInfo(groundOverlayBounds1.mapsId, mapId: mapId))!; + final GroundOverlay groundOverlayBoundsInfo2 = (await inspector + .getGroundOverlayInfo(groundOverlayBounds2.mapsId, mapId: mapId))!; + final GroundOverlay groundOverlayPositionInfo1 = (await inspector + .getGroundOverlayInfo( groundOverlayPosition1.mapsId, mapId: mapId, ))!; @@ -1797,13 +1785,10 @@ void main() { await tester.pumpAndSettle(const Duration(seconds: 3)); if (inspector.supportsGettingGroundOverlayInfo()) { - final GroundOverlay groundOverlayBounds1Info = - (await inspector.getGroundOverlayInfo( - groundOverlayBounds1.mapsId, - mapId: mapId, - ))!; - final GroundOverlay groundOverlayPosition1Info = - (await inspector.getGroundOverlayInfo( + final GroundOverlay groundOverlayBounds1Info = (await inspector + .getGroundOverlayInfo(groundOverlayBounds1.mapsId, mapId: mapId))!; + final GroundOverlay groundOverlayPosition1Info = (await inspector + .getGroundOverlayInfo( groundOverlayPosition1.mapsId, mapId: mapId, ))!; diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/ios14/pubspec.yaml b/packages/google_maps_flutter/google_maps_flutter_ios/example/ios14/pubspec.yaml index fa834998717..d4192ad9642 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/ios14/pubspec.yaml +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/ios14/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the google_maps_flutter plugin. publish_to: none environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: cupertino_icons: ^1.0.5 diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/ios15/pubspec.yaml b/packages/google_maps_flutter/google_maps_flutter_ios/example/ios15/pubspec.yaml index fa834998717..d4192ad9642 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/ios15/pubspec.yaml +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/ios15/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the google_maps_flutter plugin. publish_to: none environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: cupertino_icons: ^1.0.5 diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/animate_camera.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/animate_camera.dart index 95b132fe9e6..a7c515c3692 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/animate_camera.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/animate_camera.dart @@ -40,10 +40,9 @@ class AnimateCameraState extends State { void _toggleAnimationDuration() { setState(() { - _cameraUpdateAnimationDuration = - _cameraUpdateAnimationDuration != null - ? null - : const Duration(seconds: _durationSeconds); + _cameraUpdateAnimationDuration = _cameraUpdateAnimationDuration != null + ? null + : const Duration(seconds: _durationSeconds); }); } diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/clustering.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/clustering.dart index 17b2cfee09a..e7ed25a3043 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/clustering.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/clustering.dart @@ -125,10 +125,9 @@ class ClusteringBodyState extends State { final ClusterManager clusterManager = ClusterManager( clusterManagerId: clusterManagerId, - onClusterTap: - (Cluster cluster) => setState(() { - lastCluster = cluster; - }), + onClusterTap: (Cluster cluster) => setState(() { + lastCluster = cluster; + }), ); setState(() { @@ -197,10 +196,9 @@ class ClusteringBodyState extends State { final Marker marker = markers[markerId]!; final double current = marker.alpha; markers[markerId] = marker.copyWith( - alphaParam: - current == _fullyVisibleAlpha - ? _halfVisibleAlpha - : _fullyVisibleAlpha, + alphaParam: current == _fullyVisibleAlpha + ? _halfVisibleAlpha + : _fullyVisibleAlpha, ); } setState(() {}); @@ -230,19 +228,16 @@ class ClusteringBodyState extends State { mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ TextButton( - onPressed: - clusterManagers.length >= _clusterManagerMaxCount - ? null - : () => _addClusterManager(), + onPressed: clusterManagers.length >= _clusterManagerMaxCount + ? null + : () => _addClusterManager(), child: const Text('Add cluster manager'), ), TextButton( - onPressed: - clusterManagers.isEmpty - ? null - : () => _removeClusterManager( - clusterManagers.values.last, - ), + onPressed: clusterManagers.isEmpty + ? null + : () => + _removeClusterManager(clusterManagers.values.last), child: const Text('Remove cluster manager'), ), ], @@ -263,20 +258,20 @@ class ClusteringBodyState extends State { alignment: WrapAlignment.spaceEvenly, children: [ TextButton( - onPressed: - selectedId == null - ? null - : () { - _remove(selectedId); - setState(() { - selectedMarker = null; - }); - }, + onPressed: selectedId == null + ? null + : () { + _remove(selectedId); + setState(() { + selectedMarker = null; + }); + }, child: const Text('Remove selected marker'), ), TextButton( - onPressed: - markers.isEmpty ? null : () => _changeMarkersAlpha(), + onPressed: markers.isEmpty + ? null + : () => _changeMarkersAlpha(), child: const Text('Change all markers alpha'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/ground_overlay.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/ground_overlay.dart index ee58f6edf37..8c8f5dcf159 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/ground_overlay.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/ground_overlay.dart @@ -134,8 +134,9 @@ class GroundOverlayBodyState extends State { // Adjusts the bearing by 10 degrees, wrapping around at 360 degrees. // 10 is the increment, 350 degrees of the full circle -10. _groundOverlay = _groundOverlay!.copyWith( - bearingParam: - _groundOverlay!.bearing >= 350 ? 0 : _groundOverlay!.bearing + 10, + bearingParam: _groundOverlay!.bearing >= 350 + ? 0 + : _groundOverlay!.bearing + 10, ); }); } @@ -143,8 +144,9 @@ class GroundOverlayBodyState extends State { void _changeTransparency() { assert(_groundOverlay != null); setState(() { - final double transparency = - _groundOverlay!.transparency == 0.0 ? 0.5 : 0.0; + final double transparency = _groundOverlay!.transparency == 0.0 + ? 0.5 + : 0.0; _groundOverlay = _groundOverlay!.copyWith( transparencyParam: transparency, ); @@ -155,10 +157,9 @@ class GroundOverlayBodyState extends State { assert(_groundOverlay != null); assert(_placingType == _GroundOverlayPlacing.position); setState(() { - _currentGroundOverlayPos = - _currentGroundOverlayPos == _groundOverlayPos1 - ? _groundOverlayPos2 - : _groundOverlayPos1; + _currentGroundOverlayPos = _currentGroundOverlayPos == _groundOverlayPos1 + ? _groundOverlayPos2 + : _groundOverlayPos1; }); // Re-add the ground overlay to apply the new position, as the position @@ -172,8 +173,8 @@ class GroundOverlayBodyState extends State { setState(() { _currentGroundOverlayBounds = _currentGroundOverlayBounds == _groundOverlayBounds1 - ? _groundOverlayBounds2 - : _groundOverlayBounds1; + ? _groundOverlayBounds2 + : _groundOverlayBounds1; }); // Re-add the ground overlay to apply the new position, as the position @@ -201,10 +202,9 @@ class GroundOverlayBodyState extends State { Future _changeType() async { setState(() { - _placingType = - _placingType == _GroundOverlayPlacing.position - ? _GroundOverlayPlacing.bounds - : _GroundOverlayPlacing.position; + _placingType = _placingType == _GroundOverlayPlacing.position + ? _GroundOverlayPlacing.bounds + : _GroundOverlayPlacing.position; }); // Re-add the ground overlay to apply the new position, as the position @@ -215,10 +215,9 @@ class GroundOverlayBodyState extends State { Future _changeAnchor() async { assert(_groundOverlay != null); setState(() { - _anchor = - _groundOverlay!.anchor == const Offset(0.5, 0.5) - ? const Offset(1.0, 1.0) - : const Offset(0.5, 0.5); + _anchor = _groundOverlay!.anchor == const Offset(0.5, 0.5) + ? const Offset(1.0, 1.0) + : const Offset(0.5, 0.5); }); // Re-add the ground overlay to apply the new anchor, as anchor cannot be @@ -263,8 +262,9 @@ class GroundOverlayBodyState extends State { alignment: WrapAlignment.spaceEvenly, children: [ TextButton( - onPressed: - _groundOverlay == null ? null : () => _changeTransparency(), + onPressed: _groundOverlay == null + ? null + : () => _changeTransparency(), child: const Text('change transparency'), ), TextButton( @@ -294,17 +294,17 @@ class GroundOverlayBodyState extends State { TextButton( onPressed: _placingType != _GroundOverlayPlacing.position || - _groundOverlay == null - ? null - : () => _changePosition(), + _groundOverlay == null + ? null + : () => _changePosition(), child: const Text('change position'), ), TextButton( onPressed: _placingType != _GroundOverlayPlacing.bounds || - _groundOverlay == null - ? null - : () => _changeBounds(), + _groundOverlay == null + ? null + : () => _changeBounds(), child: const Text('change bounds'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/map_ui.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/map_ui.dart index ebddc1819dd..53109eeac4d 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/map_ui.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/map_ui.dart @@ -91,10 +91,9 @@ class MapUiBodyState extends State { ), onPressed: () { setState(() { - _cameraTargetBounds = - _cameraTargetBounds.bounds == null - ? CameraTargetBounds(sydneyBounds) - : CameraTargetBounds.unbounded; + _cameraTargetBounds = _cameraTargetBounds.bounds == null + ? CameraTargetBounds(sydneyBounds) + : CameraTargetBounds.unbounded; }); }, ); @@ -107,10 +106,9 @@ class MapUiBodyState extends State { ), onPressed: () { setState(() { - _minMaxZoomPreference = - _minMaxZoomPreference.minZoom == null - ? const MinMaxZoomPreference(12.0, 16.0) - : MinMaxZoomPreference.unbounded; + _minMaxZoomPreference = _minMaxZoomPreference.minZoom == null + ? const MinMaxZoomPreference(12.0, 16.0) + : MinMaxZoomPreference.unbounded; }); }, ); @@ -243,8 +241,9 @@ class MapUiBodyState extends State { child: Text('${_nightMode ? 'disable' : 'enable'} night mode'), onPressed: () async { _nightMode = !_nightMode; - final String style = - _nightMode ? await _getFileData('assets/night_mode.json') : ''; + final String style = _nightMode + ? await _getFileData('assets/night_mode.json') + : ''; setState(() { _mapStyle = style; }); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/maps_demo.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/maps_demo.dart index 42eaeb1832f..6d21ab3b91e 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/maps_demo.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/maps_demo.dart @@ -17,9 +17,10 @@ class MapsDemo extends StatelessWidget { void _pushPage(BuildContext context, GoogleMapExampleAppPage page) { Navigator.of(context).push( MaterialPageRoute( - builder: - (_) => - Scaffold(appBar: AppBar(title: Text(page.title)), body: page), + builder: (_) => Scaffold( + appBar: AppBar(title: Text(page.title)), + body: page, + ), ), ); } @@ -30,12 +31,11 @@ class MapsDemo extends StatelessWidget { appBar: AppBar(title: const Text('GoogleMaps examples')), body: ListView.builder( itemCount: pages.length, - itemBuilder: - (_, int index) => ListTile( - leading: pages[index].leading, - title: Text(pages[index].title), - onTap: () => _pushPage(context, pages[index]), - ), + itemBuilder: (_, int index) => ListTile( + leading: pages[index].leading, + title: Text(pages[index].title), + onTap: () => _pushPage(context, pages[index]), + ), ), ); } diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/marker_icons.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/marker_icons.dart index ccb58231fa1..40df30c94ac 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/marker_icons.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/marker_icons.dart @@ -112,15 +112,14 @@ class MarkerIconsBodyState extends State { }); } }, - items: - _MarkerSizeOption.values.map(( - _MarkerSizeOption option, - ) { - return DropdownMenuItem<_MarkerSizeOption>( - value: option, - child: Text(_getMarkerSizeOptionName(option)), - ); - }).toList(), + items: _MarkerSizeOption.values.map(( + _MarkerSizeOption option, + ) { + return DropdownMenuItem<_MarkerSizeOption>( + value: option, + child: Text(_getMarkerSizeOptionName(option)), + ); + }).toList(), ), ], ), @@ -253,10 +252,12 @@ class MarkerIconsBodyState extends State { Future _updateMarkerAssetImage(BuildContext context) async { // Width and height are used only for custom size. - final (double? width, double? height) = - _scalingEnabled && _customSizeEnabled - ? _getCurrentMarkerSize() - : (null, null); + final ( + double? width, + double? height, + ) = _scalingEnabled && _customSizeEnabled + ? _getCurrentMarkerSize() + : (null, null); AssetMapBitmap assetMapBitmap; if (_mipMapsEnabled) { @@ -268,8 +269,9 @@ class MarkerIconsBodyState extends State { 'assets/red_square.png', width: width, height: height, - bitmapScaling: - _scalingEnabled ? MapBitmapScaling.auto : MapBitmapScaling.none, + bitmapScaling: _scalingEnabled + ? MapBitmapScaling.auto + : MapBitmapScaling.none, ); } else { // Uses hardcoded asset path @@ -279,8 +281,9 @@ class MarkerIconsBodyState extends State { 'assets/red_square.png', width: width, height: height, - bitmapScaling: - _scalingEnabled ? MapBitmapScaling.auto : MapBitmapScaling.none, + bitmapScaling: _scalingEnabled + ? MapBitmapScaling.auto + : MapBitmapScaling.none, ); } @@ -304,18 +307,21 @@ class MarkerIconsBodyState extends State { final ByteData bytes = await createCustomMarkerIconImage(size: canvasSize); // Width and height are used only for custom size. - final (double? width, double? height) = - _scalingEnabled && _customSizeEnabled - ? _getCurrentMarkerSize() - : (null, null); + final ( + double? width, + double? height, + ) = _scalingEnabled && _customSizeEnabled + ? _getCurrentMarkerSize() + : (null, null); final BytesMapBitmap bitmap = BytesMapBitmap( bytes.buffer.asUint8List(), imagePixelRatio: imagePixelRatio, width: width, height: height, - bitmapScaling: - _scalingEnabled ? MapBitmapScaling.auto : MapBitmapScaling.none, + bitmapScaling: _scalingEnabled + ? MapBitmapScaling.auto + : MapBitmapScaling.none, ); _updateBytesBitmap(bitmap); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/place_circle.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/place_circle.dart index b3090032be1..d45ec7e5c27 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/place_circle.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/place_circle.dart @@ -171,17 +171,15 @@ class PlaceCircleBodyState extends State { children: [ TextButton(onPressed: _add, child: const Text('add')), TextButton( - onPressed: - (selectedId == null) - ? null - : () => _remove(selectedId), + onPressed: (selectedId == null) + ? null + : () => _remove(selectedId), child: const Text('remove'), ), TextButton( - onPressed: - (selectedId == null) - ? null - : () => _toggleVisible(selectedId), + onPressed: (selectedId == null) + ? null + : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), ], @@ -189,24 +187,21 @@ class PlaceCircleBodyState extends State { Column( children: [ TextButton( - onPressed: - (selectedId == null) - ? null - : () => _changeStrokeWidth(selectedId), + onPressed: (selectedId == null) + ? null + : () => _changeStrokeWidth(selectedId), child: const Text('change stroke width'), ), TextButton( - onPressed: - (selectedId == null) - ? null - : () => _changeStrokeColor(selectedId), + onPressed: (selectedId == null) + ? null + : () => _changeStrokeColor(selectedId), child: const Text('change stroke color'), ), TextButton( - onPressed: - (selectedId == null) - ? null - : () => _changeFillColor(selectedId), + onPressed: (selectedId == null) + ? null + : () => _changeFillColor(selectedId), child: const Text('change fill color'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/place_marker.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/place_marker.dart index 691463d9ee0..9674927fe37 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/place_marker.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/place_marker.dart @@ -306,8 +306,9 @@ class PlaceMarkerBodyState extends State { children: [ TextButton(onPressed: _add, child: const Text('Add')), TextButton( - onPressed: - selectedId == null ? null : () => _remove(selectedId), + onPressed: selectedId == null + ? null + : () => _remove(selectedId), child: const Text('Remove'), ), ], @@ -316,82 +317,73 @@ class PlaceMarkerBodyState extends State { alignment: WrapAlignment.spaceEvenly, children: [ TextButton( - onPressed: - selectedId == null ? null : () => _changeInfo(selectedId), + onPressed: selectedId == null + ? null + : () => _changeInfo(selectedId), child: const Text('change info'), ), TextButton( - onPressed: - selectedId == null - ? null - : () => _changeInfoAnchor(selectedId), + onPressed: selectedId == null + ? null + : () => _changeInfoAnchor(selectedId), child: const Text('change info anchor'), ), TextButton( - onPressed: - selectedId == null - ? null - : () => _changeAlpha(selectedId), + onPressed: selectedId == null + ? null + : () => _changeAlpha(selectedId), child: const Text('change alpha'), ), TextButton( - onPressed: - selectedId == null - ? null - : () => _changeAnchor(selectedId), + onPressed: selectedId == null + ? null + : () => _changeAnchor(selectedId), child: const Text('change anchor'), ), TextButton( - onPressed: - selectedId == null - ? null - : () => _toggleDraggable(selectedId), + onPressed: selectedId == null + ? null + : () => _toggleDraggable(selectedId), child: const Text('toggle draggable'), ), TextButton( - onPressed: - selectedId == null ? null : () => _toggleFlat(selectedId), + onPressed: selectedId == null + ? null + : () => _toggleFlat(selectedId), child: const Text('toggle flat'), ), TextButton( - onPressed: - selectedId == null - ? null - : () => _changePosition(selectedId), + onPressed: selectedId == null + ? null + : () => _changePosition(selectedId), child: const Text('change position'), ), TextButton( - onPressed: - selectedId == null - ? null - : () => _changeRotation(selectedId), + onPressed: selectedId == null + ? null + : () => _changeRotation(selectedId), child: const Text('change rotation'), ), TextButton( - onPressed: - selectedId == null - ? null - : () => _toggleVisible(selectedId), + onPressed: selectedId == null + ? null + : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), TextButton( - onPressed: - selectedId == null - ? null - : () => _changeZIndex(selectedId), + onPressed: selectedId == null + ? null + : () => _changeZIndex(selectedId), child: const Text('change zIndex'), ), TextButton( - onPressed: - selectedId == null - ? null - : () { - _getMarkerIcon(context).then(( - BitmapDescriptor icon, - ) { - _setMarkerIcon(selectedId, icon); - }); - }, + onPressed: selectedId == null + ? null + : () { + _getMarkerIcon(context).then((BitmapDescriptor icon) { + _setMarkerIcon(selectedId, icon); + }); + }, child: const Text('set marker icon'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/place_polygon.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/place_polygon.dart index 1fffc4452f2..79475381c15 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/place_polygon.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/place_polygon.dart @@ -194,24 +194,21 @@ class PlacePolygonBodyState extends State { children: [ TextButton(onPressed: _add, child: const Text('add')), TextButton( - onPressed: - (selectedId == null) - ? null - : () => _remove(selectedId), + onPressed: (selectedId == null) + ? null + : () => _remove(selectedId), child: const Text('remove'), ), TextButton( - onPressed: - (selectedId == null) - ? null - : () => _toggleVisible(selectedId), + onPressed: (selectedId == null) + ? null + : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), TextButton( - onPressed: - (selectedId == null) - ? null - : () => _toggleGeodesic(selectedId), + onPressed: (selectedId == null) + ? null + : () => _toggleGeodesic(selectedId), child: const Text('toggle geodesic'), ), ], @@ -219,42 +216,37 @@ class PlacePolygonBodyState extends State { Column( children: [ TextButton( - onPressed: - (selectedId == null) - ? null - : (polygons[selectedId]!.holes.isNotEmpty - ? null - : () => _addHoles(selectedId)), + onPressed: (selectedId == null) + ? null + : (polygons[selectedId]!.holes.isNotEmpty + ? null + : () => _addHoles(selectedId)), child: const Text('add holes'), ), TextButton( - onPressed: - (selectedId == null) - ? null - : (polygons[selectedId]!.holes.isEmpty - ? null - : () => _removeHoles(selectedId)), + onPressed: (selectedId == null) + ? null + : (polygons[selectedId]!.holes.isEmpty + ? null + : () => _removeHoles(selectedId)), child: const Text('remove holes'), ), TextButton( - onPressed: - (selectedId == null) - ? null - : () => _changeWidth(selectedId), + onPressed: (selectedId == null) + ? null + : () => _changeWidth(selectedId), child: const Text('change stroke width'), ), TextButton( - onPressed: - (selectedId == null) - ? null - : () => _changeStrokeColor(selectedId), + onPressed: (selectedId == null) + ? null + : () => _changeStrokeColor(selectedId), child: const Text('change stroke color'), ), TextButton( - onPressed: - (selectedId == null) - ? null - : () => _changeFillColor(selectedId), + onPressed: (selectedId == null) + ? null + : () => _changeFillColor(selectedId), child: const Text('change fill color'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/place_polyline.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/place_polyline.dart index 2bfacb9c30e..854046b3053 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/place_polyline.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/place_polyline.dart @@ -237,24 +237,21 @@ class PlacePolylineBodyState extends State { children: [ TextButton(onPressed: _add, child: const Text('add')), TextButton( - onPressed: - (selectedId == null) - ? null - : () => _remove(selectedId), + onPressed: (selectedId == null) + ? null + : () => _remove(selectedId), child: const Text('remove'), ), TextButton( - onPressed: - (selectedId == null) - ? null - : () => _toggleVisible(selectedId), + onPressed: (selectedId == null) + ? null + : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), TextButton( - onPressed: - (selectedId == null) - ? null - : () => _toggleGeodesic(selectedId), + onPressed: (selectedId == null) + ? null + : () => _toggleGeodesic(selectedId), child: const Text('toggle geodesic'), ), ], @@ -262,45 +259,39 @@ class PlacePolylineBodyState extends State { Column( children: [ TextButton( - onPressed: - (selectedId == null) - ? null - : () => _changeWidth(selectedId), + onPressed: (selectedId == null) + ? null + : () => _changeWidth(selectedId), child: const Text('change width'), ), TextButton( - onPressed: - (selectedId == null) - ? null - : () => _changeColor(selectedId), + onPressed: (selectedId == null) + ? null + : () => _changeColor(selectedId), child: const Text('change color'), ), TextButton( - onPressed: - isIOS || (selectedId == null) - ? null - : () => _changeStartCap(selectedId), + onPressed: isIOS || (selectedId == null) + ? null + : () => _changeStartCap(selectedId), child: const Text('change start cap [Android only]'), ), TextButton( - onPressed: - isIOS || (selectedId == null) - ? null - : () => _changeEndCap(selectedId), + onPressed: isIOS || (selectedId == null) + ? null + : () => _changeEndCap(selectedId), child: const Text('change end cap [Android only]'), ), TextButton( - onPressed: - isIOS || (selectedId == null) - ? null - : () => _changeJointType(selectedId), + onPressed: isIOS || (selectedId == null) + ? null + : () => _changeJointType(selectedId), child: const Text('change joint type [Android only]'), ), TextButton( - onPressed: - (selectedId == null) - ? null - : () => _changePattern(selectedId), + onPressed: (selectedId == null) + ? null + : () => _changePattern(selectedId), child: const Text('change pattern'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/scrolling_map.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/scrolling_map.dart index c1970920175..57d8cd6d9ff 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/scrolling_map.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/scrolling_map.dart @@ -50,7 +50,7 @@ class ScrollingMapBody extends StatelessWidget { zoom: 11.0, ), gestureRecognizers: // - >{ + >{ Factory( () => EagerGestureRecognizer(), ), diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/snapshot.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/snapshot.dart index d003226ac5b..8fa4d67b642 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/snapshot.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/snapshot.dart @@ -57,8 +57,8 @@ class _SnapshotBodyState extends State<_SnapshotBody> { TextButton( child: const Text('Take a snapshot'), onPressed: () async { - final Uint8List? imageBytes = - await _mapController?.takeSnapshot(); + final Uint8List? imageBytes = await _mapController + ?.takeSnapshot(); setState(() { _imageBytes = imageBytes; }); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/pubspec.yaml b/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/pubspec.yaml index e61b27c1084..a0c48d88f36 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/pubspec.yaml +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/pubspec.yaml @@ -3,8 +3,8 @@ description: Shared Dart code for the example apps. publish_to: none environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: cupertino_icons: ^1.0.5 diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/lib/src/google_map_inspector_ios.dart b/packages/google_maps_flutter/google_maps_flutter_ios/lib/src/google_map_inspector_ios.dart index 220f5a85ad9..b00703f7204 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/lib/src/google_map_inspector_ios.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/lib/src/google_map_inspector_ios.dart @@ -54,8 +54,9 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { @override Future getMinMaxZoomLevels({required int mapId}) async { - final PlatformZoomRange zoomLevels = - await _inspectorProvider(mapId)!.getZoomRange(); + final PlatformZoomRange zoomLevels = await _inspectorProvider( + mapId, + )!.getZoomRange(); return MinMaxZoomPreference(zoomLevels.min, zoomLevels.max); } @@ -98,11 +99,10 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { (heatmapInfo.json as Map).cast(); return Heatmap( heatmapId: heatmapId, - data: - (json['data']! as List) - .map(deserializeWeightedLatLng) - .whereType() - .toList(), + data: (json['data']! as List) + .map(deserializeWeightedLatLng) + .whereType() + .toList(), gradient: deserializeHeatmapGradient(json['gradient']), opacity: json['opacity']! as double, radius: HeatmapRadius.fromPixels(json['radius']! as int), @@ -223,8 +223,9 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { @override Future getCameraPosition({required int mapId}) async { - final PlatformCameraPosition cameraPosition = - await _inspectorProvider(mapId)!.getCameraPosition(); + final PlatformCameraPosition cameraPosition = await _inspectorProvider( + mapId, + )!.getCameraPosition(); return CameraPosition( target: LatLng( cameraPosition.target.latitude, diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/lib/src/google_maps_flutter_ios.dart b/packages/google_maps_flutter/google_maps_flutter_ios/lib/src/google_maps_flutter_ios.dart index df3e73de04b..1794c914855 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/lib/src/google_maps_flutter_ios.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/lib/src/google_maps_flutter_ios.dart @@ -307,10 +307,9 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { }) { final Map? currentTileOverlays = _tileOverlays[mapId]; - final Set previousSet = - currentTileOverlays != null - ? currentTileOverlays.values.toSet() - : {}; + final Set previousSet = currentTileOverlays != null + ? currentTileOverlays.values.toSet() + : {}; final _TileOverlayUpdates updates = _TileOverlayUpdates.from( previousSet, newTileOverlays, @@ -501,28 +500,30 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { widgetConfiguration.initialCameraPosition, ), mapConfiguration: mapConfiguration, - initialMarkers: - mapObjects.markers.map(_platformMarkerFromMarker).toList(), - initialPolygons: - mapObjects.polygons.map(_platformPolygonFromPolygon).toList(), - initialPolylines: - mapObjects.polylines.map(_platformPolylineFromPolyline).toList(), - initialCircles: - mapObjects.circles.map(_platformCircleFromCircle).toList(), - initialHeatmaps: - mapObjects.heatmaps.map(_platformHeatmapFromHeatmap).toList(), - initialTileOverlays: - mapObjects.tileOverlays - .map(_platformTileOverlayFromTileOverlay) - .toList(), - initialClusterManagers: - mapObjects.clusterManagers - .map(_platformClusterManagerFromClusterManager) - .toList(), - initialGroundOverlays: - mapObjects.groundOverlays - .map(_platformGroundOverlayFromGroundOverlay) - .toList(), + initialMarkers: mapObjects.markers + .map(_platformMarkerFromMarker) + .toList(), + initialPolygons: mapObjects.polygons + .map(_platformPolygonFromPolygon) + .toList(), + initialPolylines: mapObjects.polylines + .map(_platformPolylineFromPolyline) + .toList(), + initialCircles: mapObjects.circles + .map(_platformCircleFromCircle) + .toList(), + initialHeatmaps: mapObjects.heatmaps + .map(_platformHeatmapFromHeatmap) + .toList(), + initialTileOverlays: mapObjects.tileOverlays + .map(_platformTileOverlayFromTileOverlay) + .toList(), + initialClusterManagers: mapObjects.clusterManagers + .map(_platformClusterManagerFromClusterManager) + .toList(), + initialGroundOverlays: mapObjects.groundOverlays + .map(_platformGroundOverlayFromGroundOverlay) + .toList(), ); return UiKitView( @@ -705,15 +706,13 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { ) { return PlatformGroundOverlay( groundOverlayId: groundOverlay.groundOverlayId.value, - anchor: - groundOverlay.anchor != null - ? _platformPointFromOffset(groundOverlay.anchor!) - : null, + anchor: groundOverlay.anchor != null + ? _platformPointFromOffset(groundOverlay.anchor!) + : null, image: platformBitmapFromBitmapDescriptor(groundOverlay.image), - position: - groundOverlay.position != null - ? _platformLatLngFromLatLng(groundOverlay.position!) - : null, + position: groundOverlay.position != null + ? _platformLatLngFromLatLng(groundOverlay.position!) + : null, bounds: _platformLatLngBoundsFromLatLngBounds(groundOverlay.bounds), visible: groundOverlay.visible, zIndex: groundOverlay.zIndex, @@ -725,12 +724,14 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { } static PlatformPolygon _platformPolygonFromPolygon(Polygon polygon) { - final List points = - polygon.points.map(_platformLatLngFromLatLng).toList(); - final List> holes = - polygon.holes.map((List hole) { - return hole.map(_platformLatLngFromLatLng).toList(); - }).toList(); + final List points = polygon.points + .map(_platformLatLngFromLatLng) + .toList(); + final List> holes = polygon.holes.map(( + List hole, + ) { + return hole.map(_platformLatLngFromLatLng).toList(); + }).toList(); return PlatformPolygon( polygonId: polygon.polygonId.value, fillColor: polygon.fillColor.value, @@ -746,10 +747,12 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { } static PlatformPolyline _platformPolylineFromPolyline(Polyline polyline) { - final List points = - polyline.points.map(_platformLatLngFromLatLng).toList(); - final List pattern = - polyline.patterns.map(platformPatternItemFromPatternItem).toList(); + final List points = polyline.points + .map(_platformLatLngFromLatLng) + .toList(); + final List pattern = polyline.patterns + .map(platformPatternItemFromPatternItem) + .toList(); return PlatformPolyline( polylineId: polyline.polylineId.value, consumesTapEvents: polyline.consumeTapEvents, @@ -983,14 +986,13 @@ class HostMapMessageHandler implements MapsCallbackApi { TileOverlayId(tileOverlayId), ); final TileProvider? tileProvider = tileOverlay?.tileProvider; - final Tile tile = - tileProvider == null - ? TileProvider.noTile - : await tileProvider.getTile( - location.x.round(), - location.y.round(), - zoom, - ); + final Tile tile = tileProvider == null + ? TileProvider.noTile + : await tileProvider.getTile( + location.x.round(), + location.y.round(), + zoom, + ); return _platformTileFromTile(tile); } @@ -1144,8 +1146,8 @@ PlatformCameraTargetBounds? _platformCameraTargetBoundsFromCameraTargetBounds( return bounds == null ? null : PlatformCameraTargetBounds( - bounds: _platformLatLngBoundsFromLatLngBounds(bounds.bounds), - ); + bounds: _platformLatLngBoundsFromLatLngBounds(bounds.bounds), + ); } PlatformTile _platformTileFromTile(Tile tile) { @@ -1188,11 +1190,11 @@ PlatformEdgeInsets? _platformEdgeInsetsFromEdgeInsets(EdgeInsets? insets) { return insets == null ? null : PlatformEdgeInsets( - top: insets.top, - bottom: insets.bottom, - left: insets.left, - right: insets.right, - ); + top: insets.top, + bottom: insets.bottom, + left: insets.left, + right: insets.right, + ); } PlatformMapConfiguration _platformMapConfigurationFromMapConfiguration( @@ -1230,8 +1232,8 @@ PlatformMapConfiguration _platformMapConfigurationFromOptionsJson( // All of these hard-coded values and structures come from // google_maps_flutter_platform_interface/lib/src/types/utils/map_configuration_serialization.dart // to support this legacy API that relied on cross-package magic strings. - final List? padding = - (options['padding'] as List?)?.cast(); + final List? padding = (options['padding'] as List?) + ?.cast(); final int? mapType = options['mapType'] as int?; return PlatformMapConfiguration( compassEnabled: options['compassEnabled'] as bool?, @@ -1249,15 +1251,14 @@ PlatformMapConfiguration _platformMapConfigurationFromOptionsJson( zoomGesturesEnabled: options['zoomGesturesEnabled'] as bool?, myLocationEnabled: options['myLocationEnabled'] as bool?, myLocationButtonEnabled: options['myLocationButtonEnabled'] as bool?, - padding: - padding == null - ? null - : PlatformEdgeInsets( - top: padding[0], - left: padding[1], - bottom: padding[2], - right: padding[3], - ), + padding: padding == null + ? null + : PlatformEdgeInsets( + top: padding[0], + left: padding[1], + bottom: padding[2], + right: padding[3], + ), indoorViewEnabled: options['indoorEnabled'] as bool?, trafficEnabled: options['trafficEnabled'] as bool?, buildingsEnabled: options['buildingsEnabled'] as bool?, @@ -1330,8 +1331,8 @@ PlatformZoomRange? _platformZoomRangeFromMinMaxZoomPreferenceJson( return null; } // See `MinMaxZoomPreference.toJson`. - final List minMaxZoom = - (zoomPrefsJson as List).cast(); + final List minMaxZoom = (zoomPrefsJson as List) + .cast(); return PlatformZoomRange(min: minMaxZoom[0], max: minMaxZoom[1]); } diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/lib/src/messages.g.dart b/packages/google_maps_flutter/google_maps_flutter_ios/lib/src/messages.g.dart index 906a76573ef..4e366683f86 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/lib/src/messages.g.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/lib/src/messages.g.dart @@ -939,12 +939,12 @@ class PlatformMapViewCreationParams { initialPolygons: (result[4] as List?)!.cast(), initialPolylines: (result[5] as List?)!.cast(), initialHeatmaps: (result[6] as List?)!.cast(), - initialTileOverlays: - (result[7] as List?)!.cast(), - initialClusterManagers: - (result[8] as List?)!.cast(), - initialGroundOverlays: - (result[9] as List?)!.cast(), + initialTileOverlays: (result[7] as List?)! + .cast(), + initialClusterManagers: (result[8] as List?)! + .cast(), + initialGroundOverlays: (result[9] as List?)! + .cast(), ); } } @@ -1575,8 +1575,9 @@ class MapsApi { /// BinaryMessenger will be used which routes to the host platform. MapsApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -2310,8 +2311,9 @@ abstract class MapsCallbackApi { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) { - messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; { final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( @@ -2880,8 +2882,9 @@ class MapsPlatformViewApi { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -2922,8 +2925,9 @@ class MapsInspectorApi { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/lib/src/serialization.dart b/packages/google_maps_flutter/google_maps_flutter_ios/lib/src/serialization.dart index 2d6575d1284..aa94f6c12b2 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/lib/src/serialization.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/lib/src/serialization.dart @@ -115,11 +115,10 @@ HeatmapGradient? deserializeHeatmapGradient(Object? json) { } assert(json is Map); final Map map = (json as Map).cast(); - final List colors = - (map[_heatmapGradientColorsKey]! as List) - .whereType() - .map((int e) => Color(e)) - .toList(); + final List colors = (map[_heatmapGradientColorsKey]! as List) + .whereType() + .map((int e) => Color(e)) + .toList(); final List startPoints = (map[_heatmapGradientStartPointsKey]! as List) .whereType() diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/pubspec.yaml b/packages/google_maps_flutter/google_maps_flutter_ios/pubspec.yaml index 50eadd0efc7..5584c8ae992 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/pubspec.yaml +++ b/packages/google_maps_flutter/google_maps_flutter_ios/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.15.5 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" flutter: plugin: diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/CHANGELOG.md b/packages/google_maps_flutter/google_maps_flutter_platform_interface/CHANGELOG.md index 3641925e578..7183bed62b7 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/CHANGELOG.md +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. + ## 2.14.0 * Adds support for disabling or moving the camera control button on web. @@ -248,4 +252,4 @@ ## 1.0.0 ... 1.0.0+5 -* Development. \ No newline at end of file +* Development. diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/method_channel/method_channel_google_maps_flutter.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/method_channel/method_channel_google_maps_flutter.dart index 7f5582eca63..67c8d78570e 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/method_channel/method_channel_google_maps_flutter.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/method_channel/method_channel_google_maps_flutter.dart @@ -386,10 +386,9 @@ class MethodChannelGoogleMapsFlutter extends GoogleMapsFlutterPlatform { }) { final Map? currentTileOverlays = _tileOverlays[mapId]; - final Set previousSet = - currentTileOverlays != null - ? currentTileOverlays.values.toSet() - : {}; + final Set previousSet = currentTileOverlays != null + ? currentTileOverlays.values.toSet() + : {}; final TileOverlayUpdates updates = TileOverlayUpdates.from( previousSet, newTileOverlays, @@ -438,10 +437,9 @@ class MethodChannelGoogleMapsFlutter extends GoogleMapsFlutterPlatform { @override Future setMapStyle(String? mapStyle, {required int mapId}) async { - final List successAndError = - (await channel( - mapId, - ).invokeMethod>('map#setStyle', mapStyle))!; + final List successAndError = (await channel( + mapId, + ).invokeMethod>('map#setStyle', mapStyle))!; final bool success = successAndError[0] as bool; if (!success) { throw MapStyleException(successAndError[1] as String); @@ -450,10 +448,9 @@ class MethodChannelGoogleMapsFlutter extends GoogleMapsFlutterPlatform { @override Future getVisibleRegion({required int mapId}) async { - final Map latLngBounds = - (await channel( - mapId, - ).invokeMapMethod('map#getVisibleRegion'))!; + final Map latLngBounds = (await channel( + mapId, + ).invokeMapMethod('map#getVisibleRegion'))!; final LatLng southwest = LatLng.fromJson(latLngBounds['southwest'])!; final LatLng northeast = LatLng.fromJson(latLngBounds['northeast'])!; @@ -465,8 +462,8 @@ class MethodChannelGoogleMapsFlutter extends GoogleMapsFlutterPlatform { LatLng latLng, { required int mapId, }) async { - final Map point = - (await channel(mapId).invokeMapMethod( + final Map point = (await channel(mapId) + .invokeMapMethod( 'map#getScreenCoordinate', latLng.toJson(), ))!; @@ -479,11 +476,9 @@ class MethodChannelGoogleMapsFlutter extends GoogleMapsFlutterPlatform { ScreenCoordinate screenCoordinate, { required int mapId, }) async { - final List latLng = - (await channel(mapId).invokeMethod>( - 'map#getLatLng', - screenCoordinate.toJson(), - ))!; + final List latLng = (await channel( + mapId, + ).invokeMethod>('map#getLatLng', screenCoordinate.toJson()))!; return LatLng(latLng[0] as double, latLng[1] as double); } @@ -546,8 +541,8 @@ class MethodChannelGoogleMapsFlutter extends GoogleMapsFlutterPlatform { Map mapOptions = const {}, }) { final Map creationParams = { - 'initialCameraPosition': - widgetConfiguration.initialCameraPosition.toMap(), + 'initialCameraPosition': widgetConfiguration.initialCameraPosition + .toMap(), 'options': mapOptions, 'markersToAdd': serializeMarkerSet(mapObjects.markers), 'polygonsToAdd': serializePolygonSet(mapObjects.polygons), @@ -561,16 +556,14 @@ class MethodChannelGoogleMapsFlutter extends GoogleMapsFlutterPlatform { if (useAndroidViewSurface) { return PlatformViewLink( viewType: 'plugins.flutter.io/google_maps', - surfaceFactory: ( - BuildContext context, - PlatformViewController controller, - ) { - return AndroidViewSurface( - controller: controller as AndroidViewController, - gestureRecognizers: widgetConfiguration.gestureRecognizers, - hitTestBehavior: PlatformViewHitTestBehavior.opaque, - ); - }, + surfaceFactory: + (BuildContext context, PlatformViewController controller) { + return AndroidViewSurface( + controller: controller as AndroidViewController, + gestureRecognizers: widgetConfiguration.gestureRecognizers, + hitTestBehavior: PlatformViewHitTestBehavior.opaque, + ); + }, onCreatePlatformView: (PlatformViewCreationParams params) { final SurfaceAndroidViewController controller = PlatformViewsService.initSurfaceAndroidView( diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/method_channel/serialization.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/method_channel/serialization.dart index 605deba0acf..66d5d24c6e4 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/method_channel/serialization.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/method_channel/serialization.dart @@ -149,11 +149,10 @@ HeatmapGradient? deserializeHeatmapGradient(Object? json) { } assert(json is Map); final Map map = (json as Map).cast(); - final List colors = - (map[_heatmapGradientColorsKey]! as List) - .whereType() - .map((int e) => Color(e)) - .toList(); + final List colors = (map[_heatmapGradientColorsKey]! as List) + .whereType() + .map((int e) => Color(e)) + .toList(); final List startPoints = (map[_heatmapGradientStartPointsKey]! as List) .whereType() diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/bitmap.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/bitmap.dart index f0318769fee..ef40f0ef751 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/bitmap.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/bitmap.dart @@ -128,10 +128,12 @@ abstract class BitmapDescriptor { assert(jsonMap['imagePixelRatio'] is double); assert(!jsonMap.containsKey('width') || jsonMap['width'] is double); assert(!jsonMap.containsKey('height') || jsonMap['height'] is double); - final double? width = - jsonMap.containsKey('width') ? jsonMap['width'] as double : null; - final double? height = - jsonMap.containsKey('height') ? jsonMap['height'] as double : null; + final double? width = jsonMap.containsKey('width') + ? jsonMap['width'] as double + : null; + final double? height = jsonMap.containsKey('height') + ? jsonMap['height'] as double + : null; return AssetMapBitmap( jsonMap['assetName'] as String, bitmapScaling: mapBitmapScalingFromString( @@ -154,10 +156,12 @@ abstract class BitmapDescriptor { assert(jsonMap['imagePixelRatio'] is double); assert(!jsonMap.containsKey('width') || jsonMap['width'] is double); assert(!jsonMap.containsKey('height') || jsonMap['height'] is double); - final double? width = - jsonMap.containsKey('width') ? jsonMap['width'] as double : null; - final double? height = - jsonMap.containsKey('height') ? jsonMap['height'] as double : null; + final double? width = jsonMap.containsKey('width') + ? jsonMap['width'] as double + : null; + final double? height = jsonMap.containsKey('height') + ? jsonMap['height'] as double + : null; return BytesMapBitmap( jsonMap['byteData'] as Uint8List, bitmapScaling: mapBitmapScalingFromString( @@ -391,10 +395,9 @@ class DefaultMarker extends BitmapDescriptor { final num? hue; @override - Object toJson() => - (hue == null) - ? const [BitmapDescriptor._defaultMarker] - : [BitmapDescriptor._defaultMarker, hue!]; + Object toJson() => (hue == null) + ? const [BitmapDescriptor._defaultMarker] + : [BitmapDescriptor._defaultMarker, hue!]; } /// A BitmapDescriptor using an array of bytes that must be encoded diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/camera.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/camera.dart index ca283f00eed..af6c5d0e45e 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/camera.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/camera.dart @@ -296,14 +296,13 @@ class CameraUpdateZoomBy extends CameraUpdate { /// Optional point around which the zoom is focused. final Offset? focus; @override - Object toJson() => - (focus == null) - ? ['zoomBy', amount] - : [ - 'zoomBy', - amount, - [focus!.dx, focus!.dy], - ]; + Object toJson() => (focus == null) + ? ['zoomBy', amount] + : [ + 'zoomBy', + amount, + [focus!.dx, focus!.dy], + ]; } /// Defines a camera zoom in. diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/location.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/location.dart index b185c8ae6c4..6879757087f 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/location.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/location.dart @@ -18,10 +18,9 @@ class LatLng { const LatLng(double latitude, double longitude) : latitude = latitude < -90.0 ? -90.0 : (90.0 < latitude ? 90.0 : latitude), // Avoids normalization if possible to prevent unnecessary loss of precision - longitude = - longitude >= -180 && longitude < 180 - ? longitude - : (longitude + 180.0) % 360.0 - 180.0; + longitude = longitude >= -180 && longitude < 180 + ? longitude + : (longitude + 180.0) % 360.0 - 180.0; /// The latitude in degrees between -90.0 and 90.0, both inclusive. final double latitude; diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/map_configuration.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/map_configuration.dart index 590d4002381..235ec580b2e 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/map_configuration.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/map_configuration.dart @@ -158,78 +158,72 @@ class MapConfiguration { return MapConfiguration( webCameraControlPosition: webCameraControlPosition != other.webCameraControlPosition - ? webCameraControlPosition - : null, + ? webCameraControlPosition + : null, webCameraControlEnabled: webCameraControlEnabled != other.webCameraControlEnabled - ? webCameraControlEnabled - : null, - webGestureHandling: - webGestureHandling != other.webGestureHandling - ? webGestureHandling - : null, - compassEnabled: - compassEnabled != other.compassEnabled ? compassEnabled : null, - mapToolbarEnabled: - mapToolbarEnabled != other.mapToolbarEnabled - ? mapToolbarEnabled - : null, - cameraTargetBounds: - cameraTargetBounds != other.cameraTargetBounds - ? cameraTargetBounds - : null, + ? webCameraControlEnabled + : null, + webGestureHandling: webGestureHandling != other.webGestureHandling + ? webGestureHandling + : null, + compassEnabled: compassEnabled != other.compassEnabled + ? compassEnabled + : null, + mapToolbarEnabled: mapToolbarEnabled != other.mapToolbarEnabled + ? mapToolbarEnabled + : null, + cameraTargetBounds: cameraTargetBounds != other.cameraTargetBounds + ? cameraTargetBounds + : null, mapType: mapType != other.mapType ? mapType : null, - minMaxZoomPreference: - minMaxZoomPreference != other.minMaxZoomPreference - ? minMaxZoomPreference - : null, + minMaxZoomPreference: minMaxZoomPreference != other.minMaxZoomPreference + ? minMaxZoomPreference + : null, rotateGesturesEnabled: rotateGesturesEnabled != other.rotateGesturesEnabled - ? rotateGesturesEnabled - : null, + ? rotateGesturesEnabled + : null, scrollGesturesEnabled: scrollGesturesEnabled != other.scrollGesturesEnabled - ? scrollGesturesEnabled - : null, - tiltGesturesEnabled: - tiltGesturesEnabled != other.tiltGesturesEnabled - ? tiltGesturesEnabled - : null, + ? scrollGesturesEnabled + : null, + tiltGesturesEnabled: tiltGesturesEnabled != other.tiltGesturesEnabled + ? tiltGesturesEnabled + : null, fortyFiveDegreeImageryEnabled: fortyFiveDegreeImageryEnabled != other.fortyFiveDegreeImageryEnabled - ? fortyFiveDegreeImageryEnabled - : null, - trackCameraPosition: - trackCameraPosition != other.trackCameraPosition - ? trackCameraPosition - : null, - zoomControlsEnabled: - zoomControlsEnabled != other.zoomControlsEnabled - ? zoomControlsEnabled - : null, - zoomGesturesEnabled: - zoomGesturesEnabled != other.zoomGesturesEnabled - ? zoomGesturesEnabled - : null, - liteModeEnabled: - liteModeEnabled != other.liteModeEnabled ? liteModeEnabled : null, - myLocationEnabled: - myLocationEnabled != other.myLocationEnabled - ? myLocationEnabled - : null, + ? fortyFiveDegreeImageryEnabled + : null, + trackCameraPosition: trackCameraPosition != other.trackCameraPosition + ? trackCameraPosition + : null, + zoomControlsEnabled: zoomControlsEnabled != other.zoomControlsEnabled + ? zoomControlsEnabled + : null, + zoomGesturesEnabled: zoomGesturesEnabled != other.zoomGesturesEnabled + ? zoomGesturesEnabled + : null, + liteModeEnabled: liteModeEnabled != other.liteModeEnabled + ? liteModeEnabled + : null, + myLocationEnabled: myLocationEnabled != other.myLocationEnabled + ? myLocationEnabled + : null, myLocationButtonEnabled: myLocationButtonEnabled != other.myLocationButtonEnabled - ? myLocationButtonEnabled - : null, + ? myLocationButtonEnabled + : null, padding: padding != other.padding ? padding : null, - indoorViewEnabled: - indoorViewEnabled != other.indoorViewEnabled - ? indoorViewEnabled - : null, - trafficEnabled: - trafficEnabled != other.trafficEnabled ? trafficEnabled : null, - buildingsEnabled: - buildingsEnabled != other.buildingsEnabled ? buildingsEnabled : null, + indoorViewEnabled: indoorViewEnabled != other.indoorViewEnabled + ? indoorViewEnabled + : null, + trafficEnabled: trafficEnabled != other.trafficEnabled + ? trafficEnabled + : null, + buildingsEnabled: buildingsEnabled != other.buildingsEnabled + ? buildingsEnabled + : null, mapId: mapId != other.mapId ? mapId : null, style: style != other.style ? style : null, markerType: markerType != other.markerType ? markerType : null, diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/maps_object_updates.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/maps_object_updates.dart index 3577ca1a829..85f9d2da4c1 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/maps_object_updates.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/maps_object_updates.dart @@ -37,11 +37,10 @@ class MapsObjectUpdates> { _objectIdsToRemove = previousObjectIds.difference(currentObjectIds); - _objectsToAdd = - currentObjectIds - .difference(previousObjectIds) - .map(idToCurrentObject) - .toSet(); + _objectsToAdd = currentObjectIds + .difference(previousObjectIds) + .map(idToCurrentObject) + .toSet(); // Returns `true` if [current] is not equals to previous one with the // same id. @@ -50,12 +49,11 @@ class MapsObjectUpdates> { return current != previous; } - _objectsToChange = - currentObjectIds - .intersection(previousObjectIds) - .map(idToCurrentObject) - .where(hasChanged) - .toSet(); + _objectsToChange = currentObjectIds + .intersection(previousObjectIds) + .map(idToCurrentObject) + .where(hasChanged) + .toSet(); } /// The name of the objects being updated, for use in serialization. diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/pubspec.yaml b/packages/google_maps_flutter/google_maps_flutter_platform_interface/pubspec.yaml index 7a8fdc763c6..9f98762bd09 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/pubspec.yaml +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/pubspec.yaml @@ -7,8 +7,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.14.0 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: collection: ^1.15.0 diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/heatmap_test.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/heatmap_test.dart index bf07b4e78d4..44f3a135b4f 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/heatmap_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/heatmap_test.dart @@ -302,10 +302,12 @@ void main() { ); expect(gradient.toJson(), { - 'colors': - colors.map((HeatmapGradientColor e) => e.color.value).toList(), - 'startPoints': - colors.map((HeatmapGradientColor e) => e.startPoint).toList(), + 'colors': colors + .map((HeatmapGradientColor e) => e.color.value) + .toList(), + 'startPoints': colors + .map((HeatmapGradientColor e) => e.startPoint) + .toList(), 'colorMapSize': colorMapSize, }); }); diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/maps_object_updates_test.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/maps_object_updates_test.dart index 38f6466b21b..c2fb440eb5e 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/maps_object_updates_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/maps_object_updates_test.dart @@ -91,10 +91,9 @@ void main() { expect(json, { 'testObjectsToAdd': serializeMapsObjectSet(updates.objectsToAdd), 'testObjectsToChange': serializeMapsObjectSet(updates.objectsToChange), - 'testObjectIdsToRemove': - updates.objectIdsToRemove - .map((MapsObjectId m) => m.value) - .toList(), + 'testObjectIdsToRemove': updates.objectIdsToRemove + .map((MapsObjectId m) => m.value) + .toList(), }); }); diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/tile_overlay_updates_test.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/tile_overlay_updates_test.dart index be3e26a2b28..b7f91c06c75 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/tile_overlay_updates_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/tile_overlay_updates_test.dart @@ -61,10 +61,9 @@ void main() { 'tileOverlaysToChange': serializeTileOverlaySet( updates.tileOverlaysToChange, ), - 'tileOverlayIdsToRemove': - updates.tileOverlayIdsToRemove - .map((TileOverlayId m) => m.value) - .toList(), + 'tileOverlayIdsToRemove': updates.tileOverlayIdsToRemove + .map((TileOverlayId m) => m.value) + .toList(), }); }); diff --git a/packages/google_maps_flutter/google_maps_flutter_web/CHANGELOG.md b/packages/google_maps_flutter/google_maps_flutter_web/CHANGELOG.md index 028ca4a0d5a..0cb861a490f 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/CHANGELOG.md +++ b/packages/google_maps_flutter/google_maps_flutter_web/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. + ## 0.5.14+3 * Replaces uses of deprecated `Color` properties. diff --git a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_controller_test.dart b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_controller_test.dart index 2cf115e0ae7..ce102173d4c 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_controller_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_controller_test.dart @@ -271,18 +271,17 @@ void main() { }); testWidgets('listens to map events', (WidgetTester tester) async { - controller = - createController() - ..debugSetOverrides( - createMap: (_, __) => map, - circles: circles, - heatmaps: heatmaps, - markers: markers, - polygons: polygons, - polylines: polylines, - groundOverlays: groundOverlays, - ) - ..init(); + controller = createController() + ..debugSetOverrides( + createMap: (_, __) => map, + circles: circles, + heatmaps: heatmaps, + markers: markers, + polygons: polygons, + polylines: polylines, + groundOverlays: groundOverlays, + ) + ..init(); // Trigger events on the map, and verify they've been broadcast to the stream final Stream> capturedEvents = stream.stream.take(5); @@ -313,18 +312,17 @@ void main() { testWidgets('stops listening to map events once disposed', ( WidgetTester tester, ) async { - controller = - createController() - ..debugSetOverrides( - createMap: (_, __) => map, - circles: circles, - heatmaps: heatmaps, - markers: markers, - polygons: polygons, - polylines: polylines, - groundOverlays: groundOverlays, - ) - ..init(); + controller = createController() + ..debugSetOverrides( + createMap: (_, __) => map, + circles: circles, + heatmaps: heatmaps, + markers: markers, + polygons: polygons, + polylines: polylines, + groundOverlays: groundOverlays, + ) + ..init(); controller.dispose(); @@ -353,19 +351,18 @@ void main() { testWidgets("binds geometry controllers to map's", ( WidgetTester tester, ) async { - controller = - createController() - ..debugSetOverrides( - createMap: (_, __) => map, - circles: circles, - heatmaps: heatmaps, - markers: markers, - polygons: polygons, - polylines: polylines, - tileOverlays: tileOverlays, - groundOverlays: groundOverlays, - ) - ..init(); + controller = createController() + ..debugSetOverrides( + createMap: (_, __) => map, + circles: circles, + heatmaps: heatmaps, + markers: markers, + polygons: polygons, + polylines: polylines, + tileOverlays: tileOverlays, + groundOverlays: groundOverlays, + ) + ..init(); verify(circles.bindToMap(mapId, map)); verify(heatmaps.bindToMap(mapId, map)); @@ -462,18 +459,17 @@ void main() { }, ); - controller = - createController(mapObjects: mapObjects) - ..debugSetOverrides( - circles: circles, - heatmaps: heatmaps, - markers: markers, - polygons: polygons, - polylines: polylines, - tileOverlays: tileOverlays, - groundOverlays: groundOverlays, - ) - ..init(); + controller = createController(mapObjects: mapObjects) + ..debugSetOverrides( + circles: circles, + heatmaps: heatmaps, + markers: markers, + polygons: polygons, + polylines: polylines, + tileOverlays: tileOverlays, + groundOverlays: groundOverlays, + ) + ..init(); verify(circles.addCircles(mapObjects.circles)); verify(heatmaps.addHeatmaps(mapObjects.heatmaps)); @@ -793,10 +789,9 @@ void main() { ..zoom = 10 ..center = gmaps.LatLng(0, 0), ); - controller = - createController() - ..debugSetOverrides(createMap: (_, __) => map) - ..init(); + controller = createController() + ..debugSetOverrides(createMap: (_, __) => map) + ..init(); }); group('updateMapConfiguration', () { @@ -1127,8 +1122,8 @@ void main() { testWidgets('updateGroundOverlays', (WidgetTester tester) async { final MockGroundOverlaysController mock = MockGroundOverlaysController(); - controller = - createController()..debugSetOverrides(groundOverlays: mock); + controller = createController() + ..debugSetOverrides(groundOverlays: mock); final LatLngBounds bounds = LatLngBounds( northeast: const LatLng(100, 0), diff --git a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_plugin_test.dart b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_plugin_test.dart index f7f4c2c5220..a70ef4e73c9 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_plugin_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_plugin_test.dart @@ -189,8 +189,9 @@ void main() { await plugin.setMapStyle(mapStyle, mapId: 0); - final dynamic captured = - verify(controller.updateStyles(captureThat(isList))).captured[0]; + final dynamic captured = verify( + controller.updateStyles(captureThat(isList)), + ).captured[0]; final List styles = captured as List; diff --git a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/marker_clustering_test.dart b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/marker_clustering_test.dart index 0fb3e61b81d..c2c650156b1 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/marker_clustering_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/marker_clustering_test.dart @@ -180,7 +180,9 @@ Future _pumpMap( Widget _wrapMap(Widget map, [Size size = const Size.square(200)]) { return MaterialApp( home: Scaffold( - body: Center(child: SizedBox.fromSize(size: size, child: map)), + body: Center( + child: SizedBox.fromSize(size: size, child: map), + ), ), ); } diff --git a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/marker_test.dart b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/marker_test.dart index ce86f70ac32..ad74c151d64 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/marker_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/marker_test.dart @@ -103,10 +103,9 @@ void main() { testWidgets('update', (WidgetTester tester) async { final MarkerController controller = MarkerController(marker: marker); - final gmaps.MarkerOptions options = - gmaps.MarkerOptions() - ..draggable = true - ..position = gmaps.LatLng(42, 54); + final gmaps.MarkerOptions options = gmaps.MarkerOptions() + ..draggable = true + ..position = gmaps.LatLng(42, 54); expect(marker.isDraggableDefined(), isFalse); @@ -176,8 +175,8 @@ void main() { testWidgets('cannot call update after remove', ( WidgetTester tester, ) async { - final gmaps.MarkerOptions options = - gmaps.MarkerOptions()..draggable = true; + final gmaps.MarkerOptions options = gmaps.MarkerOptions() + ..draggable = true; controller.remove(); diff --git a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/projection_test.dart b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/projection_test.dart index ec70151642e..b3a61c4419d 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/projection_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/projection_test.dart @@ -100,8 +100,8 @@ void main() { final GoogleMapController controller = await controllerCompleter.future; - final LatLngBounds firstVisibleRegion = - await controller.getVisibleRegion(); + final LatLngBounds firstVisibleRegion = await controller + .getVisibleRegion(); expect(firstVisibleRegion, isNotNull); expect(firstVisibleRegion.southwest, isNotNull); @@ -115,8 +115,8 @@ void main() { ); await tester.pumpAndSettle(const Duration(seconds: 3)); - final LatLngBounds secondVisibleRegion = - await controller.getVisibleRegion(); + final LatLngBounds secondVisibleRegion = await controller + .getVisibleRegion(); expect(secondVisibleRegion, isNotNull); expect(secondVisibleRegion, isNot(zeroLatLngBounds)); diff --git a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/shape_test.dart b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/shape_test.dart index 5dbec6bab15..2816fa9c2d3 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/shape_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/shape_test.dart @@ -52,8 +52,8 @@ void main() { testWidgets('update', (WidgetTester tester) async { final CircleController controller = CircleController(circle: circle); - final gmaps.CircleOptions options = - gmaps.CircleOptions()..draggable = true; + final gmaps.CircleOptions options = gmaps.CircleOptions() + ..draggable = true; expect(circle.isDraggableDefined(), isFalse); @@ -78,8 +78,8 @@ void main() { testWidgets('cannot call update after remove', ( WidgetTester tester, ) async { - final gmaps.CircleOptions options = - gmaps.CircleOptions()..draggable = true; + final gmaps.CircleOptions options = gmaps.CircleOptions() + ..draggable = true; controller.remove(); @@ -109,8 +109,8 @@ void main() { testWidgets('update', (WidgetTester tester) async { final PolygonController controller = PolygonController(polygon: polygon); - final gmaps.PolygonOptions options = - gmaps.PolygonOptions()..draggable = true; + final gmaps.PolygonOptions options = gmaps.PolygonOptions() + ..draggable = true; expect(polygon.isDraggableDefined(), isFalse); @@ -135,8 +135,8 @@ void main() { testWidgets('cannot call update after remove', ( WidgetTester tester, ) async { - final gmaps.PolygonOptions options = - gmaps.PolygonOptions()..draggable = true; + final gmaps.PolygonOptions options = gmaps.PolygonOptions() + ..draggable = true; controller.remove(); @@ -172,8 +172,8 @@ void main() { final PolylineController controller = PolylineController( polyline: polyline, ); - final gmaps.PolylineOptions options = - gmaps.PolylineOptions()..draggable = true; + final gmaps.PolylineOptions options = gmaps.PolylineOptions() + ..draggable = true; expect(polyline.isDraggableDefined(), isFalse); @@ -198,8 +198,8 @@ void main() { testWidgets('cannot call update after remove', ( WidgetTester tester, ) async { - final gmaps.PolylineOptions options = - gmaps.PolylineOptions()..draggable = true; + final gmaps.PolylineOptions options = gmaps.PolylineOptions() + ..draggable = true; controller.remove(); diff --git a/packages/google_maps_flutter/google_maps_flutter_web/example/pubspec.yaml b/packages/google_maps_flutter/google_maps_flutter_web/example/pubspec.yaml index 96e889984d0..addf03ad32e 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/example/pubspec.yaml +++ b/packages/google_maps_flutter/google_maps_flutter_web/example/pubspec.yaml @@ -2,8 +2,8 @@ name: google_maps_flutter_web_integration_tests publish_to: none environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/convert.dart b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/convert.dart index 4c234b8646c..b647d95a988 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/convert.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/convert.dart @@ -193,11 +193,10 @@ List _mapStyles(String? mapStyleJson) { _isJsonMapStyle(value as Map)) { List stylers = []; if (value['stylers'] != null) { - stylers = - (value['stylers']! as List) - .whereType>() - .map(MapStyler.fromJson) - .toList(); + stylers = (value['stylers']! as List) + .whereType>() + .map(MapStyler.fromJson) + .toList(); } return gmaps.MapTypeStyle() ..elementType = value['elementType'] as String? @@ -270,9 +269,8 @@ gmaps.InfoWindowOptions? _infoWindowOptionsFromMarker(Marker marker) { // Add an outer wrapper to the contents of the infowindow, we need it to listen // to click events... - final HTMLElement container = - createDivElement() - ..id = 'gmaps-marker-${marker.markerId.value}-infowindow'; + final HTMLElement container = createDivElement() + ..id = 'gmaps-marker-${marker.markerId.value}-infowindow'; if (markerTitle.isNotEmpty) { final HTMLHeadingElement title = @@ -282,8 +280,8 @@ gmaps.InfoWindowOptions? _infoWindowOptionsFromMarker(Marker marker) { container.appendChild(title); } if (markerSnippet.isNotEmpty) { - final HTMLElement snippet = - createDivElement()..className = 'infowindow-snippet'; + final HTMLElement snippet = createDivElement() + ..className = 'infowindow-snippet'; // Firefox and Safari don't support Trusted Types yet. // See https://developer.mozilla.org/en-US/docs/Web/API/TrustedTypePolicyFactory#browser_compatibility @@ -291,10 +289,9 @@ gmaps.InfoWindowOptions? _infoWindowOptionsFromMarker(Marker marker) { _gmapsTrustedTypePolicy ??= window.trustedTypes.createPolicy( 'google_maps_flutter_sanitize', TrustedTypePolicyOptions( - createHTML: - (String html) { - return sanitizeHtml(html).toJS; - }.toJS, + createHTML: (String html) { + return sanitizeHtml(html).toJS; + }.toJS, ), ); @@ -459,9 +456,8 @@ Future _gmIconFromBitmapDescriptor( assert(iconConfig.length >= 2); // iconConfig[2] contains the DPIs of the screen, but that information is // already encoded in the iconConfig[1] - icon = - gmaps.Icon() - ..url = ui_web.assetManager.getAssetUrl(iconConfig[1]! as String); + icon = gmaps.Icon() + ..url = ui_web.assetManager.getAssetUrl(iconConfig[1]! as String); final gmaps.Size? size = _gmSizeFromIconConfig(iconConfig, 3); if (size != null) { @@ -520,18 +516,17 @@ Future _markerOptionsFromMarker( } gmaps.CircleOptions _circleOptionsFromCircle(Circle circle) { - final gmaps.CircleOptions circleOptions = - gmaps.CircleOptions() - ..strokeColor = _getCssColor(circle.strokeColor) - ..strokeOpacity = _getCssOpacity(circle.strokeColor) - ..strokeWeight = circle.strokeWidth - ..fillColor = _getCssColor(circle.fillColor) - ..fillOpacity = _getCssOpacity(circle.fillColor) - ..center = gmaps.LatLng(circle.center.latitude, circle.center.longitude) - ..radius = circle.radius - ..visible = circle.visible - ..zIndex = circle.zIndex - ..clickable = circle.consumeTapEvents; + final gmaps.CircleOptions circleOptions = gmaps.CircleOptions() + ..strokeColor = _getCssColor(circle.strokeColor) + ..strokeOpacity = _getCssOpacity(circle.strokeColor) + ..strokeWeight = circle.strokeWidth + ..fillColor = _getCssColor(circle.fillColor) + ..fillOpacity = _getCssOpacity(circle.fillColor) + ..center = gmaps.LatLng(circle.center.latitude, circle.center.longitude) + ..radius = circle.radius + ..visible = circle.visible + ..zIndex = circle.zIndex + ..clickable = circle.consumeTapEvents; return circleOptions; } @@ -541,28 +536,22 @@ visualization.HeatmapLayerOptions _heatmapOptionsFromHeatmap(Heatmap heatmap) { ); final visualization.HeatmapLayerOptions heatmapOptions = visualization.HeatmapLayerOptions() - ..data = - heatmap.data - .map( - (WeightedLatLng e) => - visualization.WeightedLocation() - ..location = gmaps.LatLng( - e.point.latitude, - e.point.longitude, - ) - ..weight = e.weight, - ) - .toList() - .toJS + ..data = heatmap.data + .map( + (WeightedLatLng e) => visualization.WeightedLocation() + ..location = gmaps.LatLng(e.point.latitude, e.point.longitude) + ..weight = e.weight, + ) + .toList() + .toJS ..dissipating = heatmap.dissipating - ..gradient = - gradientColors == null - ? null - : [ - // Web needs a first color with 0 alpha - gradientColors.first.withAlpha(0), - ...gradientColors, - ].map(_getCssColorWithAlpha).toList() + ..gradient = gradientColors == null + ? null + : [ + // Web needs a first color with 0 alpha + gradientColors.first.withAlpha(0), + ...gradientColors, + ].map(_getCssColorWithAlpha).toList() ..maxIntensity = heatmap.maxIntensity ..opacity = heatmap.opacity ..radius = heatmap.radius.radius; @@ -574,8 +563,9 @@ gmaps.PolygonOptions _polygonOptionsFromPolygon( Polygon polygon, ) { // Convert all points to GmLatLng - final List path = - polygon.points.map(_latLngToGmLatLng).toList(); + final List path = polygon.points + .map(_latLngToGmLatLng) + .toList(); final bool isClockwisePolygon = _isPolygonClockwise(path); @@ -654,8 +644,9 @@ gmaps.PolylineOptions _polylineOptionsFromPolyline( gmaps.Map googleMap, Polyline polyline, ) { - final List paths = - polyline.points.map(_latLngToGmLatLng).toList(); + final List paths = polyline.points + .map(_latLngToGmLatLng) + .toList(); return gmaps.PolylineOptions() ..path = paths.toJS @@ -720,8 +711,9 @@ void _applyCameraUpdate(gmaps.Map map, CameraUpdate update) { gmaps.LatLng? focusLatLng; final double zoomDelta = json[1] as double? ?? 0; // Web only supports integer changes... - final int newZoomDelta = - zoomDelta < 0 ? zoomDelta.floor() : zoomDelta.ceil(); + final int newZoomDelta = zoomDelta < 0 + ? zoomDelta.floor() + : zoomDelta.ceil(); if (json.length == 3) { final List latLng = asJsonList(json[2]); // With focus @@ -766,10 +758,9 @@ String urlFromMapBitmap(MapBitmap mapBitmap) { (final AssetMapBitmap assetMapBitmap) => ui_web.assetManager.getAssetUrl( assetMapBitmap.assetName, ), - _ => - throw UnimplementedError( - 'Only BytesMapBitmap and AssetMapBitmap are supported.', - ), + _ => throw UnimplementedError( + 'Only BytesMapBitmap and AssetMapBitmap are supported.', + ), }; } diff --git a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/google_maps_controller.dart b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/google_maps_controller.dart index 9a1aedcf639..b7ee0ebc0e7 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/google_maps_controller.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/google_maps_controller.dart @@ -54,11 +54,10 @@ class GoogleMapController { // Register the view factory that will hold the `_div` that holds the map in the DOM. // The `_div` needs to be created outside of the ViewFactory (and cached!) so we can // use it to create the [gmaps.Map] in the `init()` method of this class. - _div = - createDivElement() - ..id = _getViewType(mapId) - ..style.width = '100%' - ..style.height = '100%'; + _div = createDivElement() + ..id = _getViewType(mapId) + ..style.width = '100%' + ..style.height = '100%'; ui_web.platformViewRegistry.registerViewFactory( _getViewType(mapId), diff --git a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/marker_clustering.dart b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/marker_clustering.dart index 388648a307b..0f235dfc615 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/marker_clustering.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/marker_clustering.dart @@ -137,13 +137,12 @@ class ClusterManagersController extends GeometryController { markerClustererCluster.bounds!, ); - final List markerIds = - markerClustererCluster.markers - .map( - (gmaps.Marker marker) => - MarkerId((marker.get('markerId')! as JSString).toDart), - ) - .toList(); + final List markerIds = markerClustererCluster.markers + .map( + (gmaps.Marker marker) => + MarkerId((marker.get('markerId')! as JSString).toDart), + ) + .toList(); return Cluster( clusterManagerId, markerIds, diff --git a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/marker_clustering_js_interop.dart b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/marker_clustering_js_interop.dart index bc74bca2492..8d15f3546b3 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/marker_clustering_js_interop.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/marker_clustering_js_interop.dart @@ -30,16 +30,15 @@ extension type MarkerClustererOptions._(JSObject _) implements JSObject { }) => MarkerClustererOptions._js( map: map as JSAny?, markers: markers?.cast().toJS ?? JSArray(), - onClusterClick: - onClusterClick != null - ? ((JSAny event, MarkerClustererCluster cluster, JSAny map) => - onClusterClick( - event as gmaps.MapMouseEvent, - cluster, - map as gmaps.Map, - )) - .toJS - : null, + onClusterClick: onClusterClick != null + ? ((JSAny event, MarkerClustererCluster cluster, JSAny map) => + onClusterClick( + event as gmaps.MapMouseEvent, + cluster, + map as gmaps.Map, + )) + .toJS + : null, ); external factory MarkerClustererOptions._js({ diff --git a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/markers.dart b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/markers.dart index a066aabba51..2b69cc2e47b 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/markers.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/markers.dart @@ -46,10 +46,9 @@ class MarkersController extends GeometryController { infoWindowOptions.content is HTMLElement) { final HTMLElement content = infoWindowOptions.content! as HTMLElement; - content.onclick = - (JSAny? _) { - _onInfoWindowTap(marker.markerId); - }.toJS; + content.onclick = (JSAny? _) { + _onInfoWindowTap(marker.markerId); + }.toJS; } } diff --git a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/overlay.dart b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/overlay.dart index 9a5983e0acf..48f0be5c7ef 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/overlay.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/overlay.dart @@ -25,10 +25,9 @@ class TileOverlayController { /// [TileOverlay]. void update(TileOverlay tileOverlay) { _tileOverlay = tileOverlay; - _gmMapType = - gmaps.MapType() - ..tileSize = gmaps.Size(logicalTileSize, logicalTileSize) - ..getTile = _getTile; + _gmMapType = gmaps.MapType() + ..tileSize = gmaps.Size(logicalTileSize, logicalTileSize) + ..getTile = _getTile; } /// Renders a Tile for gmaps; delegating to the configured [TileProvider]. @@ -58,11 +57,10 @@ class TileOverlayController { Blob([tile.data!.toJS].toJS) as JSObject, ); img.src = src; - img.onload = - (JSAny? _) { - img.hidden = false.toJS; - URL.revokeObjectURL(src); - }.toJS; + img.onload = (JSAny? _) { + img.hidden = false.toJS; + URL.revokeObjectURL(src); + }.toJS; }); return img; diff --git a/packages/google_maps_flutter/google_maps_flutter_web/pubspec.yaml b/packages/google_maps_flutter/google_maps_flutter_web/pubspec.yaml index fe1f6554088..fee2e779f67 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/pubspec.yaml +++ b/packages/google_maps_flutter/google_maps_flutter_web/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 0.5.14+3 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" flutter: plugin: diff --git a/packages/google_sign_in/google_sign_in/CHANGELOG.md b/packages/google_sign_in/google_sign_in/CHANGELOG.md index d3e6c62eb4c..e85a56edbab 100644 --- a/packages/google_sign_in/google_sign_in/CHANGELOG.md +++ b/packages/google_sign_in/google_sign_in/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. + ## 7.2.0 * Adds a `clearAuthorizationToken` method to remove an access token from the diff --git a/packages/google_sign_in/google_sign_in/example/lib/main.dart b/packages/google_sign_in/google_sign_in/example/lib/main.dart index bcaa5912e28..401c69e9f5d 100644 --- a/packages/google_sign_in/google_sign_in/example/lib/main.dart +++ b/packages/google_sign_in/google_sign_in/example/lib/main.dart @@ -77,11 +77,11 @@ class _SignInDemoState extends State { ) async { // #docregion CheckAuthorization final GoogleSignInAccount? user = // ... - // #enddocregion CheckAuthorization - switch (event) { - GoogleSignInAuthenticationEventSignIn() => event.user, - GoogleSignInAuthenticationEventSignOut() => null, - }; + // #enddocregion CheckAuthorization + switch (event) { + GoogleSignInAuthenticationEventSignIn() => event.user, + GoogleSignInAuthenticationEventSignOut() => null, + }; // Check for existing authorization. // #docregion CheckAuthorization @@ -107,10 +107,9 @@ class _SignInDemoState extends State { setState(() { _currentUser = null; _isAuthorized = false; - _errorMessage = - e is GoogleSignInException - ? _errorMessageFromSignInException(e) - : 'Unknown error: $e'; + _errorMessage = e is GoogleSignInException + ? _errorMessageFromSignInException(e) + : 'Unknown error: $e'; }); } diff --git a/packages/google_sign_in/google_sign_in/example/pubspec.yaml b/packages/google_sign_in/google_sign_in/example/pubspec.yaml index 51bf7520b75..7a0cad831f8 100644 --- a/packages/google_sign_in/google_sign_in/example/pubspec.yaml +++ b/packages/google_sign_in/google_sign_in/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Example of Google Sign-In plugin. publish_to: none environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/google_sign_in/google_sign_in/lib/google_sign_in.dart b/packages/google_sign_in/google_sign_in/lib/google_sign_in.dart index a602c40df0c..8cee5167858 100644 --- a/packages/google_sign_in/google_sign_in/lib/google_sign_in.dart +++ b/packages/google_sign_in/google_sign_in/lib/google_sign_in.dart @@ -236,8 +236,8 @@ class GoogleSignInAuthorizationClient { return tokens == null ? null : GoogleSignInServerAuthorization( - serverAuthCode: tokens.serverAuthCode, - ); + serverAuthCode: tokens.serverAuthCode, + ); } /// Removes the given [accessToken] from any local authorization caches. diff --git a/packages/google_sign_in/google_sign_in/lib/src/fife.dart b/packages/google_sign_in/google_sign_in/lib/src/fife.dart index 846624cfce6..13e774649f6 100644 --- a/packages/google_sign_in/google_sign_in/lib/src/fife.dart +++ b/packages/google_sign_in/google_sign_in/lib/src/fife.dart @@ -46,12 +46,11 @@ String addSizeDirectiveToUrl(String photoUrl, double size) { final String baseUrl = imagePath.substring(0, directiveSeparator); final String directive = imagePath.substring(directiveSeparator + 1); // Split the directive by "-" - final Set directives = - Set.from(directive.split('-')) - // Remove the size directive, if present, and any empty values - ..removeWhere((String s) => s.isEmpty || sizeDirective.hasMatch(s)) - // Add the size and crop directives - ..addAll(['c', 's${size.round()}']); + final Set directives = Set.from(directive.split('-')) + // Remove the size directive, if present, and any empty values + ..removeWhere((String s) => s.isEmpty || sizeDirective.hasMatch(s)) + // Add the size and crop directives + ..addAll(['c', 's${size.round()}']); // Recompose the URL by performing the reverse of the parsing pathSegments.last = '$baseUrl=${directives.join("-")}'; } else { diff --git a/packages/google_sign_in/google_sign_in/lib/widgets.dart b/packages/google_sign_in/google_sign_in/lib/widgets.dart index 6b20be001ea..c78a82636df 100644 --- a/packages/google_sign_in/google_sign_in/lib/widgets.dart +++ b/packages/google_sign_in/google_sign_in/lib/widgets.dart @@ -79,13 +79,10 @@ class GoogleUserCircleAvatar extends StatelessWidget { identity.email, '-', ]; - final String placeholderChar = - placeholderCharSources - .firstWhere( - (String? str) => str != null && str.trimLeft().isNotEmpty, - )! - .trimLeft()[0] - .toUpperCase(); + final String placeholderChar = placeholderCharSources + .firstWhere((String? str) => str != null && str.trimLeft().isNotEmpty)! + .trimLeft()[0] + .toUpperCase(); final Widget placeholder = Center( child: Text(placeholderChar, textAlign: TextAlign.center), ); diff --git a/packages/google_sign_in/google_sign_in/pubspec.yaml b/packages/google_sign_in/google_sign_in/pubspec.yaml index 56283530e42..4474b6a80e0 100644 --- a/packages/google_sign_in/google_sign_in/pubspec.yaml +++ b/packages/google_sign_in/google_sign_in/pubspec.yaml @@ -6,8 +6,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 7.2.0 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" flutter: plugin: diff --git a/packages/google_sign_in/google_sign_in/test/google_sign_in_test.dart b/packages/google_sign_in/google_sign_in/test/google_sign_in_test.dart index 8eb363f64c1..d831bdb21d3 100644 --- a/packages/google_sign_in/google_sign_in/test/google_sign_in_test.dart +++ b/packages/google_sign_in/google_sign_in/test/google_sign_in_test.dart @@ -296,8 +296,8 @@ void main() { ), ); - final Future? signInFuture = - googleSignIn.attemptLightweightAuthentication(); + final Future? signInFuture = googleSignIn + .attemptLightweightAuthentication(); expect(signInFuture, isNotNull); final GoogleSignInAccount? signIn = await signInFuture; expect(signIn?.displayName, defaultUser.displayName); @@ -414,8 +414,8 @@ void main() { when(mockPlatform.attemptLightweightAuthentication(any)).thenReturn(null); - final Future? signInFuture = - googleSignIn.attemptLightweightAuthentication(); + final Future? signInFuture = googleSignIn + .attemptLightweightAuthentication(); expect(signInFuture, isNull); }); @@ -426,8 +426,8 @@ void main() { mockPlatform.attemptLightweightAuthentication(any), ).thenAnswer((_) async => null); - final Future? signInFuture = - googleSignIn.attemptLightweightAuthentication(); + final Future? signInFuture = googleSignIn + .attemptLightweightAuthentication(); expect(signInFuture, isNotNull); final GoogleSignInAccount? signIn = await signInFuture; expect(signIn, isNull); @@ -513,8 +513,8 @@ void main() { ).thenAnswer((_) async => null); await googleSignIn.initialize(); - final GoogleSignInAccount authentication = - await googleSignIn.authenticate(); + final GoogleSignInAccount authentication = await googleSignIn + .authenticate(); const List scopes = ['scope1', 'scope2']; await authentication.authorizationClient.authorizationForScopes(scopes); @@ -599,8 +599,8 @@ void main() { ); await googleSignIn.initialize(); - final GoogleSignInAccount authentication = - await googleSignIn.authenticate(); + final GoogleSignInAccount authentication = await googleSignIn + .authenticate(); const List scopes = ['scope1', 'scope2']; await authentication.authorizationClient.authorizeScopes(scopes); @@ -691,8 +691,8 @@ void main() { ).thenAnswer((_) async => null); await googleSignIn.initialize(); - final GoogleSignInAccount authentication = - await googleSignIn.authenticate(); + final GoogleSignInAccount authentication = await googleSignIn + .authenticate(); const List scopes = ['scope1', 'scope2']; await authentication.authorizationClient.authorizeServer(scopes); diff --git a/packages/google_sign_in/google_sign_in_platform_interface/CHANGELOG.md b/packages/google_sign_in/google_sign_in_platform_interface/CHANGELOG.md index 5ba9a7471ae..0a42d135deb 100644 --- a/packages/google_sign_in/google_sign_in_platform_interface/CHANGELOG.md +++ b/packages/google_sign_in/google_sign_in_platform_interface/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. + ## 3.1.0 * Adds a `clearAuthorizationToken` method to remove an access token from the diff --git a/packages/google_sign_in/google_sign_in_platform_interface/pubspec.yaml b/packages/google_sign_in/google_sign_in_platform_interface/pubspec.yaml index 6d6037ee0ed..7fd146db32b 100644 --- a/packages/google_sign_in/google_sign_in_platform_interface/pubspec.yaml +++ b/packages/google_sign_in/google_sign_in_platform_interface/pubspec.yaml @@ -7,8 +7,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 3.1.0 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/google_sign_in/google_sign_in_web/CHANGELOG.md b/packages/google_sign_in/google_sign_in_web/CHANGELOG.md index 61adeae6f5e..685d26d56c1 100644 --- a/packages/google_sign_in/google_sign_in_web/CHANGELOG.md +++ b/packages/google_sign_in/google_sign_in_web/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. + ## 1.1.0 * Adds support for the `clearAuthorizationToken` method. diff --git a/packages/google_sign_in/google_sign_in_web/example/integration_test/flexible_size_html_element_view_test_disabled.dart b/packages/google_sign_in/google_sign_in_web/example/integration_test/flexible_size_html_element_view_test_disabled.dart index b9d85e5fd70..e19ca94cd5e 100644 --- a/packages/google_sign_in/google_sign_in_web/example/integration_test/flexible_size_html_element_view_test_disabled.dart +++ b/packages/google_sign_in/google_sign_in_web/example/integration_test/flexible_size_html_element_view_test_disabled.dart @@ -161,8 +161,9 @@ Future pumpResizableWidget( await tester.pump(); // Return the element we just pumped - final Iterable elements = - find.byKey(Key('resizable_from_js_$widgetFactoryNumber')).evaluate(); + final Iterable elements = find + .byKey(Key('resizable_from_js_$widgetFactoryNumber')) + .evaluate(); expect(elements, hasLength(1)); return elements.first; } diff --git a/packages/google_sign_in/google_sign_in_web/example/integration_test/google_sign_in_web_test.dart b/packages/google_sign_in/google_sign_in_web/example/integration_test/google_sign_in_web_test.dart index 7f939e1b9bd..5eefbdc759b 100644 --- a/packages/google_sign_in/google_sign_in_web/example/integration_test/google_sign_in_web_test.dart +++ b/packages/google_sign_in/google_sign_in_web/example/integration_test/google_sign_in_web_test.dart @@ -212,18 +212,17 @@ void main() { ), ); - final List arguments = - mockito - .verify( - mockGis.requestScopes( - mockito.captureAny, - promptIfUnauthorized: mockito.captureAnyNamed( - 'promptIfUnauthorized', - ), - userHint: mockito.captureAnyNamed('userHint'), - ), - ) - .captured; + final List arguments = mockito + .verify( + mockGis.requestScopes( + mockito.captureAny, + promptIfUnauthorized: mockito.captureAnyNamed( + 'promptIfUnauthorized', + ), + userHint: mockito.captureAnyNamed('userHint'), + ), + ) + .captured; expect(token?.accessToken, someAccessToken); @@ -256,18 +255,17 @@ void main() { ), ); - final List arguments = - mockito - .verify( - mockGis.requestScopes( - mockito.captureAny, - promptIfUnauthorized: mockito.captureAnyNamed( - 'promptIfUnauthorized', - ), - userHint: mockito.captureAnyNamed('userHint'), - ), - ) - .captured; + final List arguments = mockito + .verify( + mockGis.requestScopes( + mockito.captureAny, + promptIfUnauthorized: mockito.captureAnyNamed( + 'promptIfUnauthorized', + ), + userHint: mockito.captureAnyNamed('userHint'), + ), + ) + .captured; expect(token?.accessToken, someAccessToken); @@ -319,10 +317,9 @@ void main() { ), ); - final List arguments = - mockito - .verify(mockGis.requestServerAuthCode(mockito.captureAny)) - .captured; + final List arguments = mockito + .verify(mockGis.requestServerAuthCode(mockito.captureAny)) + .captured; expect(token?.serverAuthCode, someAuthCode); @@ -365,10 +362,9 @@ void main() { const ClearAuthorizationTokenParams(accessToken: someToken), ); - final List arguments = - mockito - .verify(mockGis.clearAuthorizationToken(mockito.captureAny)) - .captured; + final List arguments = mockito + .verify(mockGis.clearAuthorizationToken(mockito.captureAny)) + .captured; expect(arguments.first, someToken); }); diff --git a/packages/google_sign_in/google_sign_in_web/example/lib/src/button_configuration_column.dart b/packages/google_sign_in/google_sign_in_web/example/lib/src/button_configuration_column.dart index 5660944f9e1..b6a87a467ed 100644 --- a/packages/google_sign_in/google_sign_in_web/example/lib/src/button_configuration_column.dart +++ b/packages/google_sign_in/google_sign_in_web/example/lib/src/button_configuration_column.dart @@ -99,9 +99,8 @@ Widget renderWebButtonConfiguration( child: ListView.builder( controller: scrollController, itemCount: _cards.length, - itemBuilder: - (BuildContext _, int index) => - _cards[index](currentConfig, onChange), + itemBuilder: (BuildContext _, int index) => + _cards[index](currentConfig, onChange), ), ), ); @@ -119,15 +118,14 @@ Widget _renderLocaleCard({ Padding( padding: const EdgeInsets.symmetric(horizontal: 16), child: DropdownButton( - items: - locales - .map( - (String locale) => DropdownMenuItem( - value: locale, - child: Text(locale), - ), - ) - .toList(), + items: locales + .map( + (String locale) => DropdownMenuItem( + value: locale, + child: Text(locale), + ), + ) + .toList(), value: value, onChanged: onChanged, isExpanded: true, @@ -177,18 +175,17 @@ Widget _renderRadioListTileCard({ onChanged: onChanged ?? (_) {}, child: Column( mainAxisSize: MainAxisSize.min, - children: - values - .map( - (T value) => RadioListTile( - value: value, - selected: value == selected, - title: Text(value.name), - enabled: onChanged != null, - dense: true, - ), - ) - .toList(), + children: values + .map( + (T value) => RadioListTile( + value: value, + selected: value == selected, + title: Text(value.name), + enabled: onChanged != null, + dense: true, + ), + ) + .toList(), ), ), ], @@ -224,8 +221,9 @@ GSIButtonConfiguration _copyConfigWith( ) { return GSIButtonConfiguration( locale: value is String ? value : old?.locale, - minimumWidth: - value is double ? (value == 0 ? null : value) : old?.minimumWidth, + minimumWidth: value is double + ? (value == 0 ? null : value) + : old?.minimumWidth, type: value is GSIButtonType ? value : old?.type, theme: value is GSIButtonTheme ? value : old?.theme, size: value is GSIButtonSize ? value : old?.size, diff --git a/packages/google_sign_in/google_sign_in_web/example/pubspec.yaml b/packages/google_sign_in/google_sign_in_web/example/pubspec.yaml index 1309d4f5b62..9d4ec1f172b 100644 --- a/packages/google_sign_in/google_sign_in_web/example/pubspec.yaml +++ b/packages/google_sign_in/google_sign_in_web/example/pubspec.yaml @@ -2,8 +2,8 @@ name: google_sign_in_web_integration_tests publish_to: none environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: cupertino_icons: ^1.0.2 diff --git a/packages/google_sign_in/google_sign_in_web/pubspec.yaml b/packages/google_sign_in/google_sign_in_web/pubspec.yaml index fb7536ced4b..cd849dcdc5c 100644 --- a/packages/google_sign_in/google_sign_in_web/pubspec.yaml +++ b/packages/google_sign_in/google_sign_in_web/pubspec.yaml @@ -6,8 +6,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 1.1.0 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" flutter: plugin: diff --git a/packages/image_picker/image_picker/CHANGELOG.md b/packages/image_picker/image_picker/CHANGELOG.md index e13b83ffe75..935de8615a9 100644 --- a/packages/image_picker/image_picker/CHANGELOG.md +++ b/packages/image_picker/image_picker/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. + ## 1.2.1 * Fixes README description of plugin suggesting that only Android and iOS is supported. diff --git a/packages/image_picker/image_picker/example/lib/main.dart b/packages/image_picker/image_picker/example/lib/main.dart index 4651f158f18..8ea29057129 100755 --- a/packages/image_picker/image_picker/example/lib/main.dart +++ b/packages/image_picker/image_picker/example/lib/main.dart @@ -113,20 +113,19 @@ class _MyHomePageState extends State { int? limit, ) async { try { - final List pickedFileList = - isMedia - ? await _picker.pickMultipleMedia( - maxWidth: maxWidth, - maxHeight: maxHeight, - imageQuality: quality, - limit: limit, - ) - : await _picker.pickMultiImage( - maxWidth: maxWidth, - maxHeight: maxHeight, - imageQuality: quality, - limit: limit, - ); + final List pickedFileList = isMedia + ? await _picker.pickMultipleMedia( + maxWidth: maxWidth, + maxHeight: maxHeight, + imageQuality: quality, + limit: limit, + ) + : await _picker.pickMultiImage( + maxWidth: maxWidth, + maxHeight: maxHeight, + imageQuality: quality, + limit: limit, + ); setState(() { _mediaFileList = pickedFileList; }); @@ -249,23 +248,25 @@ class _MyHomePageState extends State { // See https://pub.dev/packages/image_picker_for_web#limitations-on-the-web-platform return Semantics( label: 'image_picker_example_picked_image', - child: - kIsWeb - ? Image.network(_mediaFileList![index].path) - : (mime == null || mime.startsWith('image/') - ? Image.file( + child: kIsWeb + ? Image.network(_mediaFileList![index].path) + : (mime == null || mime.startsWith('image/') + ? Image.file( File(_mediaFileList![index].path), - errorBuilder: ( - BuildContext context, - Object error, - StackTrace? stackTrace, - ) { - return const Center( - child: Text('This image type is not supported'), - ); - }, + errorBuilder: + ( + BuildContext context, + Object error, + StackTrace? stackTrace, + ) { + return const Center( + child: Text( + 'This image type is not supported', + ), + ); + }, ) - : _buildInlineVideoPlayer(index)), + : _buildInlineVideoPlayer(index)), ); }, itemCount: _mediaFileList!.length, @@ -333,39 +334,35 @@ class _MyHomePageState extends State { return Scaffold( appBar: AppBar(title: Text(widget.title!)), body: Center( - child: - !kIsWeb && defaultTargetPlatform == TargetPlatform.android - ? FutureBuilder( - future: retrieveLostData(), - builder: ( - BuildContext context, - AsyncSnapshot snapshot, - ) { - switch (snapshot.connectionState) { - case ConnectionState.none: - case ConnectionState.waiting: + child: !kIsWeb && defaultTargetPlatform == TargetPlatform.android + ? FutureBuilder( + future: retrieveLostData(), + builder: (BuildContext context, AsyncSnapshot snapshot) { + switch (snapshot.connectionState) { + case ConnectionState.none: + case ConnectionState.waiting: + return const Text( + 'You have not yet picked an image.', + textAlign: TextAlign.center, + ); + case ConnectionState.done: + return _handlePreview(); + case ConnectionState.active: + if (snapshot.hasError) { + return Text( + 'Pick image/video error: ${snapshot.error}}', + textAlign: TextAlign.center, + ); + } else { return const Text( 'You have not yet picked an image.', textAlign: TextAlign.center, ); - case ConnectionState.done: - return _handlePreview(); - case ConnectionState.active: - if (snapshot.hasError) { - return Text( - 'Pick image/video error: ${snapshot.error}}', - textAlign: TextAlign.center, - ); - } else { - return const Text( - 'You have not yet picked an image.', - textAlign: TextAlign.center, - ); - } - } - }, - ) - : _handlePreview(), + } + } + }, + ) + : _handlePreview(), ), floatingActionButton: Column( mainAxisAlignment: MainAxisAlignment.end, @@ -560,22 +557,18 @@ class _MyHomePageState extends State { TextButton( child: const Text('PICK'), onPressed: () { - final double? width = - maxWidthController.text.isNotEmpty - ? double.parse(maxWidthController.text) - : null; - final double? height = - maxHeightController.text.isNotEmpty - ? double.parse(maxHeightController.text) - : null; - final int? quality = - qualityController.text.isNotEmpty - ? int.parse(qualityController.text) - : null; - final int? limit = - limitController.text.isNotEmpty - ? int.parse(limitController.text) - : null; + final double? width = maxWidthController.text.isNotEmpty + ? double.parse(maxWidthController.text) + : null; + final double? height = maxHeightController.text.isNotEmpty + ? double.parse(maxHeightController.text) + : null; + final int? quality = qualityController.text.isNotEmpty + ? int.parse(qualityController.text) + : null; + final int? limit = limitController.text.isNotEmpty + ? int.parse(limitController.text) + : null; onPick(width, height, quality, limit); Navigator.of(context).pop(); }, diff --git a/packages/image_picker/image_picker/example/pubspec.yaml b/packages/image_picker/image_picker/example/pubspec.yaml index 6b736e428b6..85c3b5129f4 100644 --- a/packages/image_picker/image_picker/example/pubspec.yaml +++ b/packages/image_picker/image_picker/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the image_picker plugin. publish_to: none environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/image_picker/image_picker/pubspec.yaml b/packages/image_picker/image_picker/pubspec.yaml index 798ab74c6ae..368fb8da09d 100755 --- a/packages/image_picker/image_picker/pubspec.yaml +++ b/packages/image_picker/image_picker/pubspec.yaml @@ -6,8 +6,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 1.2.1 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" flutter: plugin: diff --git a/packages/image_picker/image_picker_for_web/CHANGELOG.md b/packages/image_picker/image_picker_for_web/CHANGELOG.md index 4abc12d19aa..01e7a642f42 100644 --- a/packages/image_picker/image_picker_for_web/CHANGELOG.md +++ b/packages/image_picker/image_picker_for_web/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 3.1.0 diff --git a/packages/image_picker/image_picker_for_web/example/integration_test/image_picker_for_web_test.dart b/packages/image_picker/image_picker_for_web/example/integration_test/image_picker_for_web_test.dart index 23f37908d8f..03b98675ccf 100644 --- a/packages/image_picker/image_picker_for_web/example/integration_test/image_picker_for_web_test.dart +++ b/packages/image_picker/image_picker_for_web/example/integration_test/image_picker_for_web_test.dart @@ -43,8 +43,8 @@ void main() { }); testWidgets('getImageFromSource can select a file', (WidgetTester _) async { - final web.HTMLInputElement mockInput = - web.HTMLInputElement()..type = 'file'; + final web.HTMLInputElement mockInput = web.HTMLInputElement() + ..type = 'file'; final ImagePickerPluginTestOverrides overrides = ImagePickerPluginTestOverrides() ..createInputElement = ((_, __) => mockInput) @@ -88,14 +88,16 @@ void main() { testWidgets('getMultiImageWithOptions can select multiple files', ( WidgetTester _, ) async { - final web.HTMLInputElement mockInput = - web.HTMLInputElement()..type = 'file'; + final web.HTMLInputElement mockInput = web.HTMLInputElement() + ..type = 'file'; final ImagePickerPluginTestOverrides overrides = ImagePickerPluginTestOverrides() ..createInputElement = ((_, __) => mockInput) - ..getMultipleFilesFromInput = - ((_) => [textFile, secondTextFile]); + ..getMultipleFilesFromInput = ((_) => [ + textFile, + secondTextFile, + ]); final ImagePickerPlugin plugin = ImagePickerPlugin(overrides: overrides); @@ -119,14 +121,16 @@ void main() { }); testWidgets('getMedia can select multiple files', (WidgetTester _) async { - final web.HTMLInputElement mockInput = - web.HTMLInputElement()..type = 'file'; + final web.HTMLInputElement mockInput = web.HTMLInputElement() + ..type = 'file'; final ImagePickerPluginTestOverrides overrides = ImagePickerPluginTestOverrides() ..createInputElement = ((_, __) => mockInput) - ..getMultipleFilesFromInput = - ((_) => [textFile, secondTextFile]); + ..getMultipleFilesFromInput = ((_) => [ + textFile, + secondTextFile, + ]); final ImagePickerPlugin plugin = ImagePickerPlugin(overrides: overrides); @@ -154,14 +158,16 @@ void main() { testWidgets('getMultiVideoWithOptions can select multiple files', ( WidgetTester _, ) async { - final web.HTMLInputElement mockInput = - web.HTMLInputElement()..type = 'file'; + final web.HTMLInputElement mockInput = web.HTMLInputElement() + ..type = 'file'; final ImagePickerPluginTestOverrides overrides = ImagePickerPluginTestOverrides() ..createInputElement = ((_, __) => mockInput) - ..getMultipleFilesFromInput = - ((_) => [textFile, secondTextFile]); + ..getMultipleFilesFromInput = ((_) => [ + textFile, + secondTextFile, + ]); final ImagePickerPlugin plugin = ImagePickerPlugin(overrides: overrides); @@ -191,10 +197,9 @@ void main() { setUp(() { mockInput = web.HTMLInputElement()..type = 'file'; - overrides = - ImagePickerPluginTestOverrides() - ..createInputElement = ((_, __) => mockInput) - ..getMultipleFilesFromInput = ((_) => [textFile]); + overrides = ImagePickerPluginTestOverrides() + ..createInputElement = ((_, __) => mockInput) + ..getMultipleFilesFromInput = ((_) => [textFile]); plugin = ImagePickerPlugin(overrides: overrides); }); @@ -331,10 +336,9 @@ void main() { setUp(() { mockInput = web.HTMLInputElement()..type = 'file'; - overrides = - ImagePickerPluginTestOverrides() - ..createInputElement = ((_, __) => mockInput) - ..getMultipleFilesFromInput = ((_) => [textFile]); + overrides = ImagePickerPluginTestOverrides() + ..createInputElement = ((_, __) => mockInput) + ..getMultipleFilesFromInput = ((_) => [textFile]); plugin = ImagePickerPlugin(overrides: overrides); }); @@ -389,8 +393,10 @@ void main() { group('getMultiImage', () { testWidgets('can select multiple files', (WidgetTester _) async { // Override the returned files... - overrides.getMultipleFilesFromInput = - (_) => [textFile, secondTextFile]; + overrides.getMultipleFilesFromInput = (_) => [ + textFile, + secondTextFile, + ]; // ignore: deprecated_member_use final Future> files = plugin.getMultiImage(); diff --git a/packages/image_picker/image_picker_for_web/example/pubspec.yaml b/packages/image_picker/image_picker_for_web/example/pubspec.yaml index 03f55db879e..ccac48fa0f4 100644 --- a/packages/image_picker/image_picker_for_web/example/pubspec.yaml +++ b/packages/image_picker/image_picker_for_web/example/pubspec.yaml @@ -2,8 +2,8 @@ name: image_picker_for_web_integration_tests publish_to: none environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/image_picker/image_picker_for_web/lib/image_picker_for_web.dart b/packages/image_picker/image_picker_for_web/lib/image_picker_for_web.dart index ecdb3f09dcf..35f82fde4e2 100644 --- a/packages/image_picker/image_picker_for_web/lib/image_picker_for_web.dart +++ b/packages/image_picker/image_picker_for_web/lib/image_picker_for_web.dart @@ -61,11 +61,11 @@ class ImagePickerPlugin extends ImagePickerPlatform { return files.isEmpty ? null : _imageResizer.resizeImageIfNeeded( - files.first, - options.maxWidth, - options.maxHeight, - options.imageQuality, - ); + files.first, + options.maxWidth, + options.maxHeight, + options.imageQuality, + ); } /// Returns a [List] with the images that were picked, if any. @@ -264,37 +264,34 @@ class ImagePickerPlugin extends ImagePickerPlatform { // TODO(dit): Migrate all this to Streams (onChange, onError, onCancel) when onCancel is available. // See: https://github.com/dart-lang/web/issues/199 // Observe the input until we can return something - input.onchange = - (web.Event event) { - final List? files = _handleOnChangeEvent(event); - if (!completer.isCompleted && files != null) { - completer.complete( - files.map((web.File file) { - return XFile( - web.URL.createObjectURL(file), - name: file.name, - length: file.size, - lastModified: DateTime.fromMillisecondsSinceEpoch( - file.lastModified, - ), - mimeType: file.type, - ); - }).toList(), + input.onchange = (web.Event event) { + final List? files = _handleOnChangeEvent(event); + if (!completer.isCompleted && files != null) { + completer.complete( + files.map((web.File file) { + return XFile( + web.URL.createObjectURL(file), + name: file.name, + length: file.size, + lastModified: DateTime.fromMillisecondsSinceEpoch( + file.lastModified, + ), + mimeType: file.type, ); - } - }.toJS; - - input.oncancel = - (web.Event _) { - completer.complete([]); - }.toJS; - - input.onerror = - (web.Event event) { - if (!completer.isCompleted) { - completer.completeError(event); - } - }.toJS; + }).toList(), + ); + } + }.toJS; + + input.oncancel = (web.Event _) { + completer.complete([]); + }.toJS; + + input.onerror = (web.Event event) { + if (!completer.isCompleted) { + completer.completeError(event); + } + }.toJS; // Note that we don't bother detaching from these streams, since the // "input" gets re-created in the DOM every time the user needs to // pick a file. @@ -327,10 +324,9 @@ class ImagePickerPlugin extends ImagePickerPlatform { return _overrides!.createInputElement(accept, capture); } - final web.HTMLInputElement element = - web.HTMLInputElement() - ..type = 'file' - ..multiple = multiple; + final web.HTMLInputElement element = web.HTMLInputElement() + ..type = 'file' + ..multiple = multiple; if (accept != null) { element.accept = accept; diff --git a/packages/image_picker/image_picker_for_web/lib/src/image_resizer.dart b/packages/image_picker/image_picker_for_web/lib/src/image_resizer.dart index be6bf1c0267..d1dfd83d1fd 100644 --- a/packages/image_picker/image_picker_for_web/lib/src/image_resizer.dart +++ b/packages/image_picker/image_picker_for_web/lib/src/image_resizer.dart @@ -76,10 +76,9 @@ class ImageResizer { maxWidth, maxHeight, ); - final web.HTMLCanvasElement canvas = - web.HTMLCanvasElement() - ..width = newImageSize.width.toInt() - ..height = newImageSize.height.toInt(); + final web.HTMLCanvasElement canvas = web.HTMLCanvasElement() + ..width = newImageSize.width.toInt() + ..height = newImageSize.height.toInt(); final web.CanvasRenderingContext2D context = canvas.context2D; if (maxHeight == null && maxWidth == null) { context.drawImage(source, 0, 0); @@ -106,18 +105,17 @@ class ImageResizer { final double calculatedImageQuality = (min(imageQuality ?? 100, 100)) / 100.0; final Completer completer = Completer(); - final web.BlobCallback blobCallback = - (web.Blob blob) { - completer.complete( - XFile( - web.URL.createObjectURL(blob), - mimeType: originalFile.mimeType, - name: 'scaled_${originalFile.name}', - lastModified: DateTime.now(), - length: blob.size, - ), - ); - }.toJS; + final web.BlobCallback blobCallback = (web.Blob blob) { + completer.complete( + XFile( + web.URL.createObjectURL(blob), + mimeType: originalFile.mimeType, + name: 'scaled_${originalFile.name}', + lastModified: DateTime.now(), + length: blob.size, + ), + ); + }.toJS; canvas.toBlob( blobCallback, originalFile.mimeType ?? '', diff --git a/packages/image_picker/image_picker_for_web/lib/src/image_resizer_utils.dart b/packages/image_picker/image_picker_for_web/lib/src/image_resizer_utils.dart index 07341956d79..84ec823398c 100644 --- a/packages/image_picker/image_picker_for_web/lib/src/image_resizer_utils.dart +++ b/packages/image_picker/image_picker_for_web/lib/src/image_resizer_utils.dart @@ -30,8 +30,9 @@ Size calculateSizeOfDownScaledImage( double? maxHeight, ) { final double widthFactor = maxWidth != null ? imageSize.width / maxWidth : 1; - final double heightFactor = - maxHeight != null ? imageSize.height / maxHeight : 1; + final double heightFactor = maxHeight != null + ? imageSize.height / maxHeight + : 1; final double resizeFactor = max(widthFactor, heightFactor); return resizeFactor > 1 ? imageSize ~/ resizeFactor : imageSize; } diff --git a/packages/image_picker/image_picker_for_web/pubspec.yaml b/packages/image_picker/image_picker_for_web/pubspec.yaml index a9f2f70d506..623c3d26edc 100644 --- a/packages/image_picker/image_picker_for_web/pubspec.yaml +++ b/packages/image_picker/image_picker_for_web/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 3.1.0 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" flutter: plugin: diff --git a/packages/image_picker/image_picker_linux/CHANGELOG.md b/packages/image_picker/image_picker_linux/CHANGELOG.md index d02a6af7d60..21e9081077f 100644 --- a/packages/image_picker/image_picker_linux/CHANGELOG.md +++ b/packages/image_picker/image_picker_linux/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 0.2.2 diff --git a/packages/image_picker/image_picker_linux/example/lib/main.dart b/packages/image_picker/image_picker_linux/example/lib/main.dart index 2ca699a33f9..c78e1ba0eb9 100644 --- a/packages/image_picker/image_picker_linux/example/lib/main.dart +++ b/packages/image_picker/image_picker_linux/example/lib/main.dart @@ -110,19 +110,18 @@ class _MyHomePageState extends State { maxHeight: maxHeight, imageQuality: quality, ); - final List pickedFileList = - isMedia - ? await _picker.getMedia( - options: MediaOptions( - allowMultiple: allowMultiple, - imageOptions: imageOptions, - ), - ) - : await _picker.getMultiImageWithOptions( - options: MultiImagePickerOptions( - imageOptions: imageOptions, - ), - ); + final List pickedFileList = isMedia + ? await _picker.getMedia( + options: MediaOptions( + allowMultiple: allowMultiple, + imageOptions: imageOptions, + ), + ) + : await _picker.getMultiImageWithOptions( + options: MultiImagePickerOptions( + imageOptions: imageOptions, + ), + ); if (pickedFileList.isNotEmpty && context.mounted) { _showPickedSnackBar(context, pickedFileList); } @@ -258,21 +257,23 @@ class _MyHomePageState extends State { ), Semantics( label: 'image_picker_example_picked_image', - child: - mime == null || mime.startsWith('image/') - ? Image.file( - File(_mediaFileList![index].path), - errorBuilder: ( - BuildContext context, - Object error, - StackTrace? stackTrace, - ) { - return const Center( - child: Text('This image type is not supported'), - ); - }, - ) - : _buildInlineVideoPlayer(index), + child: mime == null || mime.startsWith('image/') + ? Image.file( + File(_mediaFileList![index].path), + errorBuilder: + ( + BuildContext context, + Object error, + StackTrace? stackTrace, + ) { + return const Center( + child: Text( + 'This image type is not supported', + ), + ); + }, + ) + : _buildInlineVideoPlayer(index), ), ], ); @@ -509,18 +510,15 @@ class _MyHomePageState extends State { TextButton( child: const Text('PICK'), onPressed: () { - final double? width = - maxWidthController.text.isNotEmpty - ? double.parse(maxWidthController.text) - : null; - final double? height = - maxHeightController.text.isNotEmpty - ? double.parse(maxHeightController.text) - : null; - final int? quality = - qualityController.text.isNotEmpty - ? int.parse(qualityController.text) - : null; + final double? width = maxWidthController.text.isNotEmpty + ? double.parse(maxWidthController.text) + : null; + final double? height = maxHeightController.text.isNotEmpty + ? double.parse(maxHeightController.text) + : null; + final int? quality = qualityController.text.isNotEmpty + ? int.parse(qualityController.text) + : null; onPick(width, height, quality); Navigator.of(context).pop(); }, diff --git a/packages/image_picker/image_picker_linux/example/pubspec.yaml b/packages/image_picker/image_picker_linux/example/pubspec.yaml index 2d9e179c859..5aeb1534a0a 100644 --- a/packages/image_picker/image_picker_linux/example/pubspec.yaml +++ b/packages/image_picker/image_picker_linux/example/pubspec.yaml @@ -4,8 +4,8 @@ publish_to: 'none' version: 1.0.0 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/image_picker/image_picker_linux/pubspec.yaml b/packages/image_picker/image_picker_linux/pubspec.yaml index b1d74b9b723..d982f07ee08 100644 --- a/packages/image_picker/image_picker_linux/pubspec.yaml +++ b/packages/image_picker/image_picker_linux/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 0.2.2 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" flutter: plugin: diff --git a/packages/image_picker/image_picker_platform_interface/CHANGELOG.md b/packages/image_picker/image_picker_platform_interface/CHANGELOG.md index e52ca570efa..0a9852125d4 100644 --- a/packages/image_picker/image_picker_platform_interface/CHANGELOG.md +++ b/packages/image_picker/image_picker_platform_interface/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. + ## 2.11.1 * Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. diff --git a/packages/image_picker/image_picker_platform_interface/lib/src/method_channel/method_channel_image_picker.dart b/packages/image_picker/image_picker_platform_interface/lib/src/method_channel/method_channel_image_picker.dart index a02109ce432..311d7e47970 100644 --- a/packages/image_picker/image_picker_platform_interface/lib/src/method_channel/method_channel_image_picker.dart +++ b/packages/image_picker/image_picker_platform_interface/lib/src/method_channel/method_channel_image_picker.dart @@ -326,8 +326,8 @@ class MethodChannelImagePicker extends ImagePickerPlatform { final String? path = result['path'] as String?; - final List? pathList = - (result['pathList'] as List?)?.cast(); + final List? pathList = (result['pathList'] as List?) + ?.cast(); if (pathList != null) { pickedFileList = []; for (final String path in pathList) { diff --git a/packages/image_picker/image_picker_platform_interface/pubspec.yaml b/packages/image_picker/image_picker_platform_interface/pubspec.yaml index 6a3c6c07b49..7338853d1fd 100644 --- a/packages/image_picker/image_picker_platform_interface/pubspec.yaml +++ b/packages/image_picker/image_picker_platform_interface/pubspec.yaml @@ -7,8 +7,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.11.1 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: cross_file: ^0.3.1+1 diff --git a/packages/image_picker/image_picker_platform_interface/test/picked_file_io_test.dart b/packages/image_picker/image_picker_platform_interface/test/picked_file_io_test.dart index fc41aeaa2c7..4e34850454e 100644 --- a/packages/image_picker/image_picker_platform_interface/test/picked_file_io_test.dart +++ b/packages/image_picker/image_picker_platform_interface/test/picked_file_io_test.dart @@ -12,8 +12,9 @@ import 'dart:typed_data'; import 'package:flutter_test/flutter_test.dart'; import 'package:image_picker_platform_interface/image_picker_platform_interface.dart'; -final String pathPrefix = - Directory.current.path.endsWith('test') ? './assets/' : './test/assets/'; +final String pathPrefix = Directory.current.path.endsWith('test') + ? './assets/' + : './test/assets/'; final String path = '${pathPrefix}hello.txt'; const String expectedStringContents = 'Hello, world!'; final Uint8List bytes = Uint8List.fromList(utf8.encode(expectedStringContents)); diff --git a/packages/image_picker/image_picker_windows/CHANGELOG.md b/packages/image_picker/image_picker_windows/CHANGELOG.md index e738b72f25c..d69fc30bd2f 100644 --- a/packages/image_picker/image_picker_windows/CHANGELOG.md +++ b/packages/image_picker/image_picker_windows/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 0.2.2 diff --git a/packages/image_picker/image_picker_windows/example/lib/main.dart b/packages/image_picker/image_picker_windows/example/lib/main.dart index 2ca699a33f9..c78e1ba0eb9 100644 --- a/packages/image_picker/image_picker_windows/example/lib/main.dart +++ b/packages/image_picker/image_picker_windows/example/lib/main.dart @@ -110,19 +110,18 @@ class _MyHomePageState extends State { maxHeight: maxHeight, imageQuality: quality, ); - final List pickedFileList = - isMedia - ? await _picker.getMedia( - options: MediaOptions( - allowMultiple: allowMultiple, - imageOptions: imageOptions, - ), - ) - : await _picker.getMultiImageWithOptions( - options: MultiImagePickerOptions( - imageOptions: imageOptions, - ), - ); + final List pickedFileList = isMedia + ? await _picker.getMedia( + options: MediaOptions( + allowMultiple: allowMultiple, + imageOptions: imageOptions, + ), + ) + : await _picker.getMultiImageWithOptions( + options: MultiImagePickerOptions( + imageOptions: imageOptions, + ), + ); if (pickedFileList.isNotEmpty && context.mounted) { _showPickedSnackBar(context, pickedFileList); } @@ -258,21 +257,23 @@ class _MyHomePageState extends State { ), Semantics( label: 'image_picker_example_picked_image', - child: - mime == null || mime.startsWith('image/') - ? Image.file( - File(_mediaFileList![index].path), - errorBuilder: ( - BuildContext context, - Object error, - StackTrace? stackTrace, - ) { - return const Center( - child: Text('This image type is not supported'), - ); - }, - ) - : _buildInlineVideoPlayer(index), + child: mime == null || mime.startsWith('image/') + ? Image.file( + File(_mediaFileList![index].path), + errorBuilder: + ( + BuildContext context, + Object error, + StackTrace? stackTrace, + ) { + return const Center( + child: Text( + 'This image type is not supported', + ), + ); + }, + ) + : _buildInlineVideoPlayer(index), ), ], ); @@ -509,18 +510,15 @@ class _MyHomePageState extends State { TextButton( child: const Text('PICK'), onPressed: () { - final double? width = - maxWidthController.text.isNotEmpty - ? double.parse(maxWidthController.text) - : null; - final double? height = - maxHeightController.text.isNotEmpty - ? double.parse(maxHeightController.text) - : null; - final int? quality = - qualityController.text.isNotEmpty - ? int.parse(qualityController.text) - : null; + final double? width = maxWidthController.text.isNotEmpty + ? double.parse(maxWidthController.text) + : null; + final double? height = maxHeightController.text.isNotEmpty + ? double.parse(maxHeightController.text) + : null; + final int? quality = qualityController.text.isNotEmpty + ? int.parse(qualityController.text) + : null; onPick(width, height, quality); Navigator.of(context).pop(); }, diff --git a/packages/image_picker/image_picker_windows/example/pubspec.yaml b/packages/image_picker/image_picker_windows/example/pubspec.yaml index 4bac1e1cef3..28b8a9a25bb 100644 --- a/packages/image_picker/image_picker_windows/example/pubspec.yaml +++ b/packages/image_picker/image_picker_windows/example/pubspec.yaml @@ -4,8 +4,8 @@ publish_to: 'none' version: 1.0.0 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/image_picker/image_picker_windows/pubspec.yaml b/packages/image_picker/image_picker_windows/pubspec.yaml index f7f6a6e8b54..15011d0efc5 100644 --- a/packages/image_picker/image_picker_windows/pubspec.yaml +++ b/packages/image_picker/image_picker_windows/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 0.2.2 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" flutter: plugin: diff --git a/packages/in_app_purchase/in_app_purchase/CHANGELOG.md b/packages/in_app_purchase/in_app_purchase/CHANGELOG.md index 8d8182da7fa..4d148ad62f5 100644 --- a/packages/in_app_purchase/in_app_purchase/CHANGELOG.md +++ b/packages/in_app_purchase/in_app_purchase/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 3.2.3 * Updates minimum `in_app_purchase_storekit` version to 0.4.0. diff --git a/packages/in_app_purchase/in_app_purchase/example/lib/main.dart b/packages/in_app_purchase/in_app_purchase/example/lib/main.dart index 2883081df97..3aecbf90b3e 100644 --- a/packages/in_app_purchase/in_app_purchase/example/lib/main.dart +++ b/packages/in_app_purchase/in_app_purchase/example/lib/main.dart @@ -193,8 +193,9 @@ class _MyAppState extends State<_MyApp> { final Widget storeHeader = ListTile( leading: Icon( _isAvailable ? Icons.check : Icons.block, - color: - _isAvailable ? Colors.green : ThemeData.light().colorScheme.error, + color: _isAvailable + ? Colors.green + : ThemeData.light().colorScheme.error, ), title: Text( 'The store is ${_isAvailable ? 'available' : 'unavailable'}.', @@ -268,58 +269,56 @@ class _MyAppState extends State<_MyApp> { return ListTile( title: Text(productDetails.title), subtitle: Text(productDetails.description), - trailing: - previousPurchase != null && Platform.isIOS - ? IconButton( - onPressed: () => confirmPriceChange(context), - icon: const Icon(Icons.upgrade), - ) - : TextButton( - style: TextButton.styleFrom( - backgroundColor: Colors.green[800], - foregroundColor: Colors.white, - ), - onPressed: () { - late PurchaseParam purchaseParam; - - if (Platform.isAndroid) { - // NOTE: If you are making a subscription purchase/upgrade/downgrade, we recommend you to - // verify the latest status of you your subscription by using server side receipt validation - // and update the UI accordingly. The subscription purchase status shown - // inside the app may not be accurate. - final GooglePlayPurchaseDetails? oldSubscription = - _getOldSubscription(productDetails, purchases); - - purchaseParam = GooglePlayPurchaseParam( - productDetails: productDetails, - changeSubscriptionParam: - (oldSubscription != null) - ? ChangeSubscriptionParam( - oldPurchaseDetails: oldSubscription, - replacementMode: - ReplacementMode.withTimeProration, - ) - : null, - ); - } else { - purchaseParam = PurchaseParam( - productDetails: productDetails, - ); - } - - if (productDetails.id == _kConsumableId) { - _inAppPurchase.buyConsumable( - purchaseParam: purchaseParam, - autoConsume: _kAutoConsume, - ); - } else { - _inAppPurchase.buyNonConsumable( - purchaseParam: purchaseParam, - ); - } - }, - child: Text(productDetails.price), + trailing: previousPurchase != null && Platform.isIOS + ? IconButton( + onPressed: () => confirmPriceChange(context), + icon: const Icon(Icons.upgrade), + ) + : TextButton( + style: TextButton.styleFrom( + backgroundColor: Colors.green[800], + foregroundColor: Colors.white, ), + onPressed: () { + late PurchaseParam purchaseParam; + + if (Platform.isAndroid) { + // NOTE: If you are making a subscription purchase/upgrade/downgrade, we recommend you to + // verify the latest status of you your subscription by using server side receipt validation + // and update the UI accordingly. The subscription purchase status shown + // inside the app may not be accurate. + final GooglePlayPurchaseDetails? oldSubscription = + _getOldSubscription(productDetails, purchases); + + purchaseParam = GooglePlayPurchaseParam( + productDetails: productDetails, + changeSubscriptionParam: (oldSubscription != null) + ? ChangeSubscriptionParam( + oldPurchaseDetails: oldSubscription, + replacementMode: + ReplacementMode.withTimeProration, + ) + : null, + ); + } else { + purchaseParam = PurchaseParam( + productDetails: productDetails, + ); + } + + if (productDetails.id == _kConsumableId) { + _inAppPurchase.buyConsumable( + purchaseParam: purchaseParam, + autoConsume: _kAutoConsume, + ); + } else { + _inAppPurchase.buyNonConsumable( + purchaseParam: purchaseParam, + ); + } + }, + child: Text(productDetails.price), + ), ); }), ); @@ -346,16 +345,15 @@ class _MyAppState extends State<_MyApp> { const ListTile consumableHeader = ListTile( title: Text('Purchased consumables'), ); - final List tokens = - _consumables.map((String id) { - return GridTile( - child: IconButton( - icon: const Icon(Icons.stars, size: 42.0, color: Colors.orange), - splashColor: Colors.yellowAccent, - onPressed: () => consume(id), - ), - ); - }).toList(); + final List tokens = _consumables.map((String id) { + return GridTile( + child: IconButton( + icon: const Icon(Icons.stars, size: 42.0, color: Colors.orange), + splashColor: Colors.yellowAccent, + onPressed: () => consume(id), + ), + ); + }).toList(); return Card( child: Column( children: [ @@ -463,11 +461,9 @@ class _MyAppState extends State<_MyApp> { } if (Platform.isAndroid) { if (!_kAutoConsume && purchaseDetails.productID == _kConsumableId) { - final InAppPurchaseAndroidPlatformAddition androidAddition = - _inAppPurchase - .getPlatformAddition< - InAppPurchaseAndroidPlatformAddition - >(); + final InAppPurchaseAndroidPlatformAddition + androidAddition = _inAppPurchase + .getPlatformAddition(); await androidAddition.consumePurchase(purchaseDetails); } } diff --git a/packages/in_app_purchase/in_app_purchase/example/pubspec.yaml b/packages/in_app_purchase/in_app_purchase/example/pubspec.yaml index 3c17c3a108c..0839b161ee8 100644 --- a/packages/in_app_purchase/in_app_purchase/example/pubspec.yaml +++ b/packages/in_app_purchase/in_app_purchase/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the in_app_purchase plugin. publish_to: none environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/in_app_purchase/in_app_purchase/pubspec.yaml b/packages/in_app_purchase/in_app_purchase/pubspec.yaml index 098173dc138..b6f4c50a65d 100644 --- a/packages/in_app_purchase/in_app_purchase/pubspec.yaml +++ b/packages/in_app_purchase/in_app_purchase/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 3.2.3 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" flutter: plugin: diff --git a/packages/in_app_purchase/in_app_purchase_platform_interface/CHANGELOG.md b/packages/in_app_purchase/in_app_purchase_platform_interface/CHANGELOG.md index 46a7364e6c5..f4dffeb7ba9 100644 --- a/packages/in_app_purchase/in_app_purchase_platform_interface/CHANGELOG.md +++ b/packages/in_app_purchase/in_app_purchase_platform_interface/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 1.4.0 diff --git a/packages/in_app_purchase/in_app_purchase_platform_interface/pubspec.yaml b/packages/in_app_purchase/in_app_purchase_platform_interface/pubspec.yaml index 45e698063d9..6d8ff12b6ba 100644 --- a/packages/in_app_purchase/in_app_purchase_platform_interface/pubspec.yaml +++ b/packages/in_app_purchase/in_app_purchase_platform_interface/pubspec.yaml @@ -7,8 +7,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 1.4.0 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/in_app_purchase/in_app_purchase_platform_interface/test/in_app_purchase_platform_test.dart b/packages/in_app_purchase/in_app_purchase_platform_interface/test/in_app_purchase_platform_test.dart index 4f08f902dec..30377ce0e93 100644 --- a/packages/in_app_purchase/in_app_purchase_platform_interface/test/in_app_purchase_platform_test.dart +++ b/packages/in_app_purchase/in_app_purchase_platform_interface/test/in_app_purchase_platform_test.dart @@ -162,9 +162,8 @@ void main() { test('Can not be a `InAppPurchasePlatform`', () { expect( - () => - InAppPurchasePlatformAddition.instance = - ExtendsInAppPurchasePlatformAdditionIsPlatformInterface(), + () => InAppPurchasePlatformAddition.instance = + ExtendsInAppPurchasePlatformAdditionIsPlatformInterface(), throwsAssertionError, ); }); @@ -173,16 +172,16 @@ void main() { ImplementsInAppPurchasePlatformAdditionProvider.register(); final ImplementsInAppPurchasePlatformAdditionProvider provider = ImplementsInAppPurchasePlatformAdditionProvider(); - final InAppPurchasePlatformAddition? addition = - provider.getPlatformAddition(); + final InAppPurchasePlatformAddition? addition = provider + .getPlatformAddition(); expect(addition.runtimeType, ExtendsInAppPurchasePlatformAddition); }); test('Provider can provide `null`', () { final ImplementsInAppPurchasePlatformAdditionProvider provider = ImplementsInAppPurchasePlatformAdditionProvider(); - final InAppPurchasePlatformAddition? addition = - provider.getPlatformAddition(); + final InAppPurchasePlatformAddition? addition = provider + .getPlatformAddition(); expect(addition, isNull); }); }); diff --git a/packages/local_auth/local_auth_platform_interface/CHANGELOG.md b/packages/local_auth/local_auth_platform_interface/CHANGELOG.md index 98be5f7598d..42419a0370e 100644 --- a/packages/local_auth/local_auth_platform_interface/CHANGELOG.md +++ b/packages/local_auth/local_auth_platform_interface/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. + ## 1.1.0 * Adds `LocalAuthException` to allow for consistent, structured exceptions diff --git a/packages/local_auth/local_auth_platform_interface/pubspec.yaml b/packages/local_auth/local_auth_platform_interface/pubspec.yaml index ca5f3aa4476..b428edfcd2f 100644 --- a/packages/local_auth/local_auth_platform_interface/pubspec.yaml +++ b/packages/local_auth/local_auth_platform_interface/pubspec.yaml @@ -7,8 +7,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 1.1.0 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/local_auth/local_auth_platform_interface/test/default_method_channel_platform_test.dart b/packages/local_auth/local_auth_platform_interface/test/default_method_channel_platform_test.dart index fdc76a62247..c538336e1fc 100644 --- a/packages/local_auth/local_auth_platform_interface/test/default_method_channel_platform_test.dart +++ b/packages/local_auth/local_auth_platform_interface/test/default_method_channel_platform_test.dart @@ -55,8 +55,8 @@ void main() { }); localAuthentication = DefaultLocalAuthPlatform(); - final bool supportsBiometrics = - await localAuthentication.deviceSupportsBiometrics(); + final bool supportsBiometrics = await localAuthentication + .deviceSupportsBiometrics(); expect(supportsBiometrics, true); expect(log, [ isMethodCall('getAvailableBiometrics', arguments: null), diff --git a/packages/local_auth/local_auth_windows/CHANGELOG.md b/packages/local_auth/local_auth_windows/CHANGELOG.md index fff29ae14f2..252df2fab72 100644 --- a/packages/local_auth/local_auth_windows/CHANGELOG.md +++ b/packages/local_auth/local_auth_windows/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. + ## 2.0.0 * Switches to `LocalAuthException` for error reporting. diff --git a/packages/local_auth/local_auth_windows/example/lib/main.dart b/packages/local_auth/local_auth_windows/example/lib/main.dart index c64205461ef..1c76c6abb15 100644 --- a/packages/local_auth/local_auth_windows/example/lib/main.dart +++ b/packages/local_auth/local_auth_windows/example/lib/main.dart @@ -34,11 +34,9 @@ class _MyAppState extends State { super.initState(); LocalAuthPlatform.instance.isDeviceSupported().then( (bool isSupported) => setState( - () => - _supportState = - isSupported - ? _SupportState.supported - : _SupportState.unsupported, + () => _supportState = isSupported + ? _SupportState.supported + : _SupportState.unsupported, ), ); } @@ -46,8 +44,8 @@ class _MyAppState extends State { Future _checkBiometrics() async { late bool deviceSupportsBiometrics; try { - deviceSupportsBiometrics = - await LocalAuthPlatform.instance.deviceSupportsBiometrics(); + deviceSupportsBiometrics = await LocalAuthPlatform.instance + .deviceSupportsBiometrics(); } on PlatformException catch (e) { deviceSupportsBiometrics = false; print(e); @@ -64,8 +62,8 @@ class _MyAppState extends State { Future _getEnrolledBiometrics() async { late List availableBiometrics; try { - availableBiometrics = - await LocalAuthPlatform.instance.getEnrolledBiometrics(); + availableBiometrics = await LocalAuthPlatform.instance + .getEnrolledBiometrics(); } on PlatformException catch (e) { availableBiometrics = []; print(e); diff --git a/packages/local_auth/local_auth_windows/example/pubspec.yaml b/packages/local_auth/local_auth_windows/example/pubspec.yaml index 1cc184db6a3..0f4e48bfbc2 100644 --- a/packages/local_auth/local_auth_windows/example/pubspec.yaml +++ b/packages/local_auth/local_auth_windows/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the local_auth_windows plugin. publish_to: none environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/local_auth/local_auth_windows/lib/local_auth_windows.dart b/packages/local_auth/local_auth_windows/lib/local_auth_windows.dart index 127e00a7822..f7255719b8c 100644 --- a/packages/local_auth/local_auth_windows/lib/local_auth_windows.dart +++ b/packages/local_auth/local_auth_windows/lib/local_auth_windows.dart @@ -42,18 +42,15 @@ class LocalAuthWindows extends LocalAuthPlatform { return switch (await _api.authenticate(localizedReason)) { AuthResult.success => true, AuthResult.failure => false, - AuthResult.noHardware => - throw const LocalAuthException( - code: LocalAuthExceptionCode.noBiometricHardware, - ), - AuthResult.notEnrolled => - throw const LocalAuthException( - code: LocalAuthExceptionCode.noBiometricsEnrolled, - ), - AuthResult.deviceBusy => - throw const LocalAuthException( - code: LocalAuthExceptionCode.biometricHardwareTemporarilyUnavailable, - ), + AuthResult.noHardware => throw const LocalAuthException( + code: LocalAuthExceptionCode.noBiometricHardware, + ), + AuthResult.notEnrolled => throw const LocalAuthException( + code: LocalAuthExceptionCode.noBiometricsEnrolled, + ), + AuthResult.deviceBusy => throw const LocalAuthException( + code: LocalAuthExceptionCode.biometricHardwareTemporarilyUnavailable, + ), AuthResult.disabledByPolicy => // This error is niche enough that it doesn't warrant a specific // mapping, so just use unknownError with a description. @@ -61,11 +58,10 @@ class LocalAuthWindows extends LocalAuthPlatform { code: LocalAuthExceptionCode.unknownError, description: 'Group policy has disabled the authentication device.', ), - AuthResult.unavailable => - throw const LocalAuthException( - code: LocalAuthExceptionCode.unknownError, - description: 'Authentication failed with an unsupported result code.', - ), + AuthResult.unavailable => throw const LocalAuthException( + code: LocalAuthExceptionCode.unknownError, + description: 'Authentication failed with an unsupported result code.', + ), }; } diff --git a/packages/local_auth/local_auth_windows/lib/src/messages.g.dart b/packages/local_auth/local_auth_windows/lib/src/messages.g.dart index 3d31a065e46..b5bd1105b07 100644 --- a/packages/local_auth/local_auth_windows/lib/src/messages.g.dart +++ b/packages/local_auth/local_auth_windows/lib/src/messages.g.dart @@ -77,8 +77,9 @@ class LocalAuthApi { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); diff --git a/packages/local_auth/local_auth_windows/pubspec.yaml b/packages/local_auth/local_auth_windows/pubspec.yaml index 7dedea02fe2..1a2c76e9969 100644 --- a/packages/local_auth/local_auth_windows/pubspec.yaml +++ b/packages/local_auth/local_auth_windows/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.0.0 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" flutter: plugin: diff --git a/packages/metrics_center/CHANGELOG.md b/packages/metrics_center/CHANGELOG.md index a06e9300afa..f93b33e247b 100644 --- a/packages/metrics_center/CHANGELOG.md +++ b/packages/metrics_center/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 1.0.14 diff --git a/packages/metrics_center/lib/src/google_benchmark.dart b/packages/metrics_center/lib/src/google_benchmark.dart index bd9186e358c..8c907c214d9 100644 --- a/packages/metrics_center/lib/src/google_benchmark.dart +++ b/packages/metrics_center/lib/src/google_benchmark.dart @@ -82,8 +82,9 @@ void _parseAnItem( rethrow; } - final double? value = - rawValue is int ? rawValue.toDouble() : rawValue as double?; + final double? value = rawValue is int + ? rawValue.toDouble() + : rawValue as double?; points.add( MetricPoint( value, diff --git a/packages/metrics_center/lib/src/skiaperf.dart b/packages/metrics_center/lib/src/skiaperf.dart index 2eadcc77b84..d218e1ebbcd 100644 --- a/packages/metrics_center/lib/src/skiaperf.dart +++ b/packages/metrics_center/lib/src/skiaperf.dart @@ -99,21 +99,21 @@ class SkiaPerfPoint extends MetricPoint { final String subResult = p.tags[kSubResultKey] ?? kSkiaPerfValueKey; - final Map options = - {}..addEntries( - p.tags.entries.where( - (MapEntry entry) => - entry.key != kGithubRepoKey && - entry.key != kGitRevisionKey && - entry.key != kNameKey && - entry.key != kSubResultKey && - // https://github.com/google/benchmark automatically generates a - // 'date' field. If it's included in options, the Skia perf won't - // be able to connect different points in a single trace because - // the date is always different. - entry.key != 'date', - ), - ); + final Map options = {} + ..addEntries( + p.tags.entries.where( + (MapEntry entry) => + entry.key != kGithubRepoKey && + entry.key != kGitRevisionKey && + entry.key != kNameKey && + entry.key != kSubResultKey && + // https://github.com/google/benchmark automatically generates a + // 'date' field. If it's included in options, the Skia perf won't + // be able to connect different points in a single trace because + // the date is always different. + entry.key != 'date', + ), + ); return SkiaPerfPoint._( githubRepo, diff --git a/packages/metrics_center/pubspec.yaml b/packages/metrics_center/pubspec.yaml index ae8e079401b..f059b9ec32c 100644 --- a/packages/metrics_center/pubspec.yaml +++ b/packages/metrics_center/pubspec.yaml @@ -6,7 +6,7 @@ repository: https://github.com/flutter/packages/tree/main/packages/metrics_cente issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+metrics_center%22 environment: - sdk: ^3.7.0 + sdk: ^3.8.0 dependencies: _discoveryapis_commons: ^1.0.0 diff --git a/packages/multicast_dns/CHANGELOG.md b/packages/multicast_dns/CHANGELOG.md index 6c4cbfa7262..a5055cd9e8b 100644 --- a/packages/multicast_dns/CHANGELOG.md +++ b/packages/multicast_dns/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 0.3.3 diff --git a/packages/multicast_dns/example/mdns_resolve.dart b/packages/multicast_dns/example/mdns_resolve.dart index e5626d33f5b..97ef0d8c88b 100644 --- a/packages/multicast_dns/example/mdns_resolve.dart +++ b/packages/multicast_dns/example/mdns_resolve.dart @@ -23,13 +23,17 @@ For example: final MDnsClient client = MDnsClient(); await client.start(); - await for (final IPAddressResourceRecord record in client - .lookup(ResourceRecordQuery.addressIPv4(name))) { + await for (final IPAddressResourceRecord record + in client.lookup( + ResourceRecordQuery.addressIPv4(name), + )) { print('Found address (${record.address}).'); } - await for (final IPAddressResourceRecord record in client - .lookup(ResourceRecordQuery.addressIPv6(name))) { + await for (final IPAddressResourceRecord record + in client.lookup( + ResourceRecordQuery.addressIPv6(name), + )) { print('Found address (${record.address}).'); } client.stop(); diff --git a/packages/multicast_dns/example/mdns_sd.dart b/packages/multicast_dns/example/mdns_sd.dart index d6e2c4fe9b0..4c4d5fea7a8 100644 --- a/packages/multicast_dns/example/mdns_sd.dart +++ b/packages/multicast_dns/example/mdns_sd.dart @@ -41,8 +41,8 @@ For example: .lookup(ResourceRecordQuery.text(ptr.domainName)) .forEach(print); } - await for (final IPAddressResourceRecord ip in client - .lookup( + await for (final IPAddressResourceRecord ip + in client.lookup( ResourceRecordQuery.addressIPv4(srv.target), )) { if (verbose) { @@ -53,8 +53,8 @@ For example: '${srv.target}:${srv.port} with ${ip.address}.', ); } - await for (final IPAddressResourceRecord ip in client - .lookup( + await for (final IPAddressResourceRecord ip + in client.lookup( ResourceRecordQuery.addressIPv6(srv.target), )) { if (verbose) { diff --git a/packages/multicast_dns/lib/multicast_dns.dart b/packages/multicast_dns/lib/multicast_dns.dart index 6c92e332912..0a0c7d74062 100644 --- a/packages/multicast_dns/lib/multicast_dns.dart +++ b/packages/multicast_dns/lib/multicast_dns.dart @@ -135,13 +135,13 @@ class MDnsClient { _ipv6InterfaceSockets.add(incoming); } - _mDnsAddress ??= - incoming.address.type == InternetAddressType.IPv4 - ? mDnsAddressIPv4 - : mDnsAddressIPv6; + _mDnsAddress ??= incoming.address.type == InternetAddressType.IPv4 + ? mDnsAddressIPv4 + : mDnsAddressIPv6; - final List interfaces = - (await interfacesFactory(listenAddress.type)).toList(); + final List interfaces = (await interfacesFactory( + listenAddress.type, + )).toList(); for (final NetworkInterface interface in interfaces) { final InternetAddress targetAddress = interface.addresses[0]; diff --git a/packages/multicast_dns/lib/src/packet.dart b/packages/multicast_dns/lib/src/packet.dart index eb5f464b282..60e1b07fe5e 100644 --- a/packages/multicast_dns/lib/src/packet.dart +++ b/packages/multicast_dns/lib/src/packet.dart @@ -50,8 +50,9 @@ List encodeMDnsQuery( assert(ResourceRecordType.debugAssertValid(type)); final List nameParts = processDnsNameParts(name); - final List> rawNameParts = - nameParts.map>((String part) => utf8.encode(part)).toList(); + final List> rawNameParts = nameParts + .map>((String part) => utf8.encode(part)) + .toList(); // Calculate the size of the packet. int size = _kHeaderSize; @@ -115,8 +116,9 @@ class _FQDNReadResult { /// Reads a FQDN from raw packet data. String readFQDN(List packet, [int offset = 0]) { - final Uint8List data = - packet is Uint8List ? packet : Uint8List.fromList(packet); + final Uint8List data = packet is Uint8List + ? packet + : Uint8List.fromList(packet); final ByteData byteData = ByteData.view(data.buffer); return _readFQDN(data, byteData, offset, data.length).fqdn; @@ -205,8 +207,9 @@ List? decodeMDnsResponse(List packet) { return null; } - final Uint8List data = - packet is Uint8List ? packet : Uint8List.fromList(packet); + final Uint8List data = packet is Uint8List + ? packet + : Uint8List.fromList(packet); final ByteData packetBytes = ByteData.view(data.buffer); final int answerCount = packetBytes.getUint16(_kAncountOffset); diff --git a/packages/multicast_dns/pubspec.yaml b/packages/multicast_dns/pubspec.yaml index 38de03aacee..b8921c68434 100644 --- a/packages/multicast_dns/pubspec.yaml +++ b/packages/multicast_dns/pubspec.yaml @@ -5,7 +5,7 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 0.3.3 environment: - sdk: ^3.7.0 + sdk: ^3.8.0 dependencies: meta: ^1.3.0 diff --git a/packages/multicast_dns/test/client_test.dart b/packages/multicast_dns/test/client_test.dart index 99730c6fc6a..79483e5ef71 100644 --- a/packages/multicast_dns/test/client_test.dart +++ b/packages/multicast_dns/test/client_test.dart @@ -14,22 +14,23 @@ void main() { late int lastPort; final FakeRawDatagramSocket datagramSocket = FakeRawDatagramSocket(); final MDnsClient client = MDnsClient( - rawDatagramSocketFactory: ( - dynamic host, - int port, { - bool reuseAddress = true, - bool reusePort = true, - int ttl = 1, - }) async { - lastPort = port; - return datagramSocket; - }, + rawDatagramSocketFactory: + ( + dynamic host, + int port, { + bool reuseAddress = true, + bool reusePort = true, + int ttl = 1, + }) async { + lastPort = port; + return datagramSocket; + }, ); await client.start( mDnsPort: 1234, - interfacesFactory: - (InternetAddressType type) async => [], + interfacesFactory: (InternetAddressType type) async => + [], ); expect(lastPort, 1234); @@ -38,21 +39,22 @@ void main() { test('Closes IPv4 sockets', () async { final FakeRawDatagramSocket datagramSocket = FakeRawDatagramSocket(); final MDnsClient client = MDnsClient( - rawDatagramSocketFactory: ( - dynamic host, - int port, { - bool reuseAddress = true, - bool reusePort = true, - int ttl = 1, - }) async { - return datagramSocket; - }, + rawDatagramSocketFactory: + ( + dynamic host, + int port, { + bool reuseAddress = true, + bool reusePort = true, + int ttl = 1, + }) async { + return datagramSocket; + }, ); await client.start( mDnsPort: 1234, - interfacesFactory: - (InternetAddressType type) async => [], + interfacesFactory: (InternetAddressType type) async => + [], ); expect(datagramSocket.closed, false); client.stop(); @@ -63,21 +65,22 @@ void main() { final FakeRawDatagramSocket datagramSocket = FakeRawDatagramSocket(); datagramSocket.address = InternetAddress.anyIPv6; final MDnsClient client = MDnsClient( - rawDatagramSocketFactory: ( - dynamic host, - int port, { - bool reuseAddress = true, - bool reusePort = true, - int ttl = 1, - }) async { - return datagramSocket; - }, + rawDatagramSocketFactory: + ( + dynamic host, + int port, { + bool reuseAddress = true, + bool reusePort = true, + int ttl = 1, + }) async { + return datagramSocket; + }, ); await client.start( mDnsPort: 1234, - interfacesFactory: - (InternetAddressType type) async => [], + interfacesFactory: (InternetAddressType type) async => + [], ); expect(datagramSocket.closed, false); client.stop(); @@ -88,20 +91,21 @@ void main() { final FakeRawDatagramSocket datagramSocket = FakeRawDatagramSocket(); datagramSocket.address = InternetAddress.anyIPv4; final MDnsClient client = MDnsClient( - rawDatagramSocketFactory: ( - dynamic host, - int port, { - bool reuseAddress = true, - bool reusePort = true, - int ttl = 1, - }) async { - return datagramSocket; - }, + rawDatagramSocketFactory: + ( + dynamic host, + int port, { + bool reuseAddress = true, + bool reusePort = true, + int ttl = 1, + }) async { + return datagramSocket; + }, ); await client.start( - interfacesFactory: - (InternetAddressType type) async => [], + interfacesFactory: (InternetAddressType type) async => + [], ); await client.start(); await client.lookup(ResourceRecordQuery.serverPointer('_')).toList(); @@ -130,16 +134,17 @@ void main() { final List selectedInterfacesForSendingPackets = []; final MDnsClient client = MDnsClient( - rawDatagramSocketFactory: ( - dynamic host, - int port, { - bool reuseAddress = true, - bool reusePort = true, - int ttl = 1, - }) async { - selectedInterfacesForSendingPackets.add(host); - return datagramSocket; - }, + rawDatagramSocketFactory: + ( + dynamic host, + int port, { + bool reuseAddress = true, + bool reusePort = true, + int ttl = 1, + }) async { + selectedInterfacesForSendingPackets.add(host); + return datagramSocket; + }, ); const int numberOfFakeInterfaces = 10; @@ -189,22 +194,23 @@ void main() { final FakeRawDatagramSocketThatSendsError datagramSocket = FakeRawDatagramSocketThatSendsError(); final MDnsClient client = MDnsClient( - rawDatagramSocketFactory: ( - dynamic host, - int port, { - bool reuseAddress = true, - bool reusePort = true, - int ttl = 1, - }) async { - return datagramSocket; - }, + rawDatagramSocketFactory: + ( + dynamic host, + int port, { + bool reuseAddress = true, + bool reusePort = true, + int ttl = 1, + }) async { + return datagramSocket; + }, ); final Completer onErrorCalledCompleter = Completer(); await client.start( mDnsPort: 1234, - interfacesFactory: - (InternetAddressType type) async => [], + interfacesFactory: (InternetAddressType type) async => + [], onError: (Object e) { expect(e, 'Error'); onErrorCalledCompleter.complete(); diff --git a/packages/multicast_dns/test/decode_test.dart b/packages/multicast_dns/test/decode_test.dart index f964c8b0f59..acadeed165d 100644 --- a/packages/multicast_dns/test/decode_test.dart +++ b/packages/multicast_dns/test/decode_test.dart @@ -129,8 +129,9 @@ void testValidPackages() { // Fixes https://github.com/flutter/flutter/issues/31854 test('Can decode packages with question, answer and additional', () { - final List result = - decodeMDnsResponse(packetWithQuestionAnArCount)!; + final List result = decodeMDnsResponse( + packetWithQuestionAnArCount, + )!; expect(result, isNotNull); expect(result.length, 2); expect(result, [ @@ -151,8 +152,9 @@ void testValidPackages() { test( 'Can decode packages without question and with answer and additional', () { - final List result = - decodeMDnsResponse(packetWithoutQuestionWithAnArCount)!; + final List result = decodeMDnsResponse( + packetWithoutQuestionWithAnArCount, + )!; expect(result, isNotNull); expect(result.length, 2); expect(result, [ diff --git a/packages/path_provider/path_provider/CHANGELOG.md b/packages/path_provider/path_provider/CHANGELOG.md index c01c866836d..0d2390c0f16 100644 --- a/packages/path_provider/path_provider/CHANGELOG.md +++ b/packages/path_provider/path_provider/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. * Updates README to indicate that Andoid SDK <21 is no longer supported. ## 2.1.5 diff --git a/packages/path_provider/path_provider/example/lib/main.dart b/packages/path_provider/path_provider/example/lib/main.dart index d1cefa481b0..e60a40e944c 100644 --- a/packages/path_provider/path_provider/example/lib/main.dart +++ b/packages/path_provider/path_provider/example/lib/main.dart @@ -193,8 +193,9 @@ class _MyHomePageState extends State { Padding( padding: const EdgeInsets.all(16.0), child: ElevatedButton( - onPressed: - Platform.isAndroid ? null : _requestAppLibraryDirectory, + onPressed: Platform.isAndroid + ? null + : _requestAppLibraryDirectory, child: Text( Platform.isAndroid ? 'Application Library Directory unavailable' @@ -228,10 +229,9 @@ class _MyHomePageState extends State { Padding( padding: const EdgeInsets.all(16.0), child: ElevatedButton( - onPressed: - !Platform.isAndroid - ? null - : _requestExternalStorageDirectory, + onPressed: !Platform.isAndroid + ? null + : _requestExternalStorageDirectory, child: Text( !Platform.isAndroid ? 'External storage is unavailable' @@ -250,14 +250,13 @@ class _MyHomePageState extends State { Padding( padding: const EdgeInsets.all(16.0), child: ElevatedButton( - onPressed: - !Platform.isAndroid - ? null - : () { - _requestExternalStorageDirectories( - StorageDirectory.music, - ); - }, + onPressed: !Platform.isAndroid + ? null + : () { + _requestExternalStorageDirectories( + StorageDirectory.music, + ); + }, child: Text( !Platform.isAndroid ? 'External directories are unavailable' @@ -276,10 +275,9 @@ class _MyHomePageState extends State { Padding( padding: const EdgeInsets.all(16.0), child: ElevatedButton( - onPressed: - !Platform.isAndroid - ? null - : _requestExternalCacheDirectories, + onPressed: !Platform.isAndroid + ? null + : _requestExternalCacheDirectories, child: Text( !Platform.isAndroid ? 'External directories are unavailable' @@ -298,10 +296,9 @@ class _MyHomePageState extends State { Padding( padding: const EdgeInsets.all(16.0), child: ElevatedButton( - onPressed: - Platform.isAndroid || Platform.isIOS - ? null - : _requestDownloadsDirectory, + onPressed: Platform.isAndroid || Platform.isIOS + ? null + : _requestDownloadsDirectory, child: Text( Platform.isAndroid || Platform.isIOS ? 'Downloads directory is unavailable' diff --git a/packages/path_provider/path_provider/example/pubspec.yaml b/packages/path_provider/path_provider/example/pubspec.yaml index 8892a58ac7a..25663b182d0 100644 --- a/packages/path_provider/path_provider/example/pubspec.yaml +++ b/packages/path_provider/path_provider/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the path_provider plugin. publish_to: none environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/path_provider/path_provider/pubspec.yaml b/packages/path_provider/path_provider/pubspec.yaml index 77ac63fb6dd..e90dc9f826e 100644 --- a/packages/path_provider/path_provider/pubspec.yaml +++ b/packages/path_provider/path_provider/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.1.5 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" flutter: plugin: diff --git a/packages/path_provider/path_provider_linux/CHANGELOG.md b/packages/path_provider/path_provider_linux/CHANGELOG.md index c7724b7ae6f..4fa3cabfe72 100644 --- a/packages/path_provider/path_provider_linux/CHANGELOG.md +++ b/packages/path_provider/path_provider_linux/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 2.2.1 diff --git a/packages/path_provider/path_provider_linux/example/pubspec.yaml b/packages/path_provider/path_provider_linux/example/pubspec.yaml index 451663c06e3..10b611c7ad0 100644 --- a/packages/path_provider/path_provider_linux/example/pubspec.yaml +++ b/packages/path_provider/path_provider_linux/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the path_provider_linux plugin. publish_to: "none" environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/path_provider/path_provider_linux/pubspec.yaml b/packages/path_provider/path_provider_linux/pubspec.yaml index 9b8f8b7622e..e49e63ef593 100644 --- a/packages/path_provider/path_provider_linux/pubspec.yaml +++ b/packages/path_provider/path_provider_linux/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.2.1 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" flutter: plugin: diff --git a/packages/path_provider/path_provider_platform_interface/CHANGELOG.md b/packages/path_provider/path_provider_platform_interface/CHANGELOG.md index 85fa835990b..1aa80031a12 100644 --- a/packages/path_provider/path_provider_platform_interface/CHANGELOG.md +++ b/packages/path_provider/path_provider_platform_interface/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 2.1.2 diff --git a/packages/path_provider/path_provider_platform_interface/pubspec.yaml b/packages/path_provider/path_provider_platform_interface/pubspec.yaml index 84360484e9e..3543f63f570 100644 --- a/packages/path_provider/path_provider_platform_interface/pubspec.yaml +++ b/packages/path_provider/path_provider_platform_interface/pubspec.yaml @@ -7,8 +7,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.1.2 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/path_provider/path_provider_platform_interface/test/method_channel_path_provider_test.dart b/packages/path_provider/path_provider_platform_interface/test/method_channel_path_provider_test.dart index 4f44066b568..b404c977fec 100644 --- a/packages/path_provider/path_provider_platform_interface/test/method_channel_path_provider_test.dart +++ b/packages/path_provider/path_provider_platform_interface/test/method_channel_path_provider_test.dart @@ -73,8 +73,8 @@ void main() { }); test('getApplicationSupportPath', () async { - final String? path = - await methodChannelPathProvider.getApplicationSupportPath(); + final String? path = await methodChannelPathProvider + .getApplicationSupportPath(); expect(log, [ isMethodCall('getApplicationSupportDirectory', arguments: null), ]); @@ -115,8 +115,8 @@ void main() { }); test('getApplicationDocumentsPath', () async { - final String? path = - await methodChannelPathProvider.getApplicationDocumentsPath(); + final String? path = await methodChannelPathProvider + .getApplicationDocumentsPath(); expect(log, [ isMethodCall('getApplicationDocumentsDirectory', arguments: null), ]); @@ -124,8 +124,8 @@ void main() { }); test('getApplicationCachePath succeeds', () async { - final String? result = - await methodChannelPathProvider.getApplicationCachePath(); + final String? result = await methodChannelPathProvider + .getApplicationCachePath(); expect(log, [ isMethodCall('getApplicationCacheDirectory', arguments: null), ]); @@ -133,8 +133,8 @@ void main() { }); test('getExternalCachePaths android succeeds', () async { - final List? result = - await methodChannelPathProvider.getExternalCachePaths(); + final List? result = await methodChannelPathProvider + .getExternalCachePaths(); expect(log, [ isMethodCall('getExternalCacheDirectories', arguments: null), ]); diff --git a/packages/path_provider/path_provider_windows/CHANGELOG.md b/packages/path_provider/path_provider_windows/CHANGELOG.md index 75dcca7713b..bdaf657695a 100644 --- a/packages/path_provider/path_provider_windows/CHANGELOG.md +++ b/packages/path_provider/path_provider_windows/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 2.3.0 diff --git a/packages/path_provider/path_provider_windows/example/pubspec.yaml b/packages/path_provider/path_provider_windows/example/pubspec.yaml index 2a6b65176f7..3f584221d8c 100644 --- a/packages/path_provider/path_provider_windows/example/pubspec.yaml +++ b/packages/path_provider/path_provider_windows/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the path_provider plugin. publish_to: none environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/path_provider/path_provider_windows/lib/src/path_provider_windows_real.dart b/packages/path_provider/path_provider_windows/lib/src/path_provider_windows_real.dart index e7bb733fce7..98df30bdf31 100644 --- a/packages/path_provider/path_provider_windows/lib/src/path_provider_windows_real.dart +++ b/packages/path_provider/path_provider_windows/lib/src/path_provider_windows_real.dart @@ -50,8 +50,8 @@ class VersionInfoQuerier { if (versionInfo == null) { return null; } - final Pointer keyPath = - '\\StringFileInfo\\$language$encoding\\$key'.toNativeUtf16(); + final Pointer keyPath = '\\StringFileInfo\\$language$encoding\\$key' + .toNativeUtf16(); final Pointer length = calloc(); final Pointer> valueAddress = calloc>(); try { @@ -189,8 +189,9 @@ class PathProviderWindows extends PathProviderPlatform { String? companyName; String? productName; - final Pointer moduleNameBuffer = - calloc(MAX_PATH + 1).cast(); + final Pointer moduleNameBuffer = calloc( + MAX_PATH + 1, + ).cast(); final Pointer unused = calloc(); Pointer? infoBuffer; try { diff --git a/packages/path_provider/path_provider_windows/pubspec.yaml b/packages/path_provider/path_provider_windows/pubspec.yaml index b2e20e6a968..7c9579d0434 100644 --- a/packages/path_provider/path_provider_windows/pubspec.yaml +++ b/packages/path_provider/path_provider_windows/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.3.0 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" flutter: plugin: diff --git a/packages/path_provider/path_provider_windows/test/guid_test.dart b/packages/path_provider/path_provider_windows/test/guid_test.dart index 5e7230abf90..9c7cbd41f6e 100644 --- a/packages/path_provider/path_provider_windows/test/guid_test.dart +++ b/packages/path_provider/path_provider_windows/test/guid_test.dart @@ -11,14 +11,13 @@ import 'package:path_provider_windows/src/guid.dart'; void main() { test('has correct byte representation', () async { - final Pointer guid = - calloc()..ref.parse('{00112233-4455-6677-8899-aabbccddeeff}'); - final ByteData data = - ByteData(16) - ..setInt32(0, guid.ref.data1, Endian.little) - ..setInt16(4, guid.ref.data2, Endian.little) - ..setInt16(6, guid.ref.data3, Endian.little) - ..setInt64(8, guid.ref.data4, Endian.little); + final Pointer guid = calloc() + ..ref.parse('{00112233-4455-6677-8899-aabbccddeeff}'); + final ByteData data = ByteData(16) + ..setInt32(0, guid.ref.data1, Endian.little) + ..setInt16(4, guid.ref.data2, Endian.little) + ..setInt16(6, guid.ref.data3, Endian.little) + ..setInt64(8, guid.ref.data4, Endian.little); expect(data.getUint8(0), 0x33); expect(data.getUint8(1), 0x22); expect(data.getUint8(2), 0x11); @@ -40,10 +39,10 @@ void main() { }); test('handles alternate forms', () async { - final Pointer guid1 = - calloc()..ref.parse('{00112233-4455-6677-8899-aabbccddeeff}'); - final Pointer guid2 = - calloc()..ref.parse('00112233445566778899AABBCCDDEEFF'); + final Pointer guid1 = calloc() + ..ref.parse('{00112233-4455-6677-8899-aabbccddeeff}'); + final Pointer guid2 = calloc() + ..ref.parse('00112233445566778899AABBCCDDEEFF'); expect(guid1.ref.data1, guid2.ref.data1); expect(guid1.ref.data2, guid2.ref.data2); diff --git a/packages/pigeon/CHANGELOG.md b/packages/pigeon/CHANGELOG.md index 6f22c5df072..895e3790bf3 100644 --- a/packages/pigeon/CHANGELOG.md +++ b/packages/pigeon/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. + ## 26.1.0 * Deprecates `dartHostTestHandler` and `dartTestOut`. diff --git a/packages/pigeon/lib/src/ast.dart b/packages/pigeon/lib/src/ast.dart index 48400707410..669d3bdca61 100644 --- a/packages/pigeon/lib/src/ast.dart +++ b/packages/pigeon/lib/src/ast.dart @@ -91,10 +91,12 @@ class Method extends Node { @override String toString() { - final String objcSelectorStr = - objcSelector.isEmpty ? '' : ' objcSelector:$objcSelector'; - final String swiftFunctionStr = - swiftFunction.isEmpty ? '' : ' swiftFunction:$swiftFunction'; + final String objcSelectorStr = objcSelector.isEmpty + ? '' + : ' objcSelector:$objcSelector'; + final String swiftFunctionStr = swiftFunction.isEmpty + ? '' + : ' swiftFunction:$swiftFunction'; return '(Method name:$name returnType:$returnType parameters:$parameters isAsynchronous:$isAsynchronous$objcSelectorStr$swiftFunctionStr documentationComments:$documentationComments)'; } } @@ -254,8 +256,9 @@ class AstProxyApi extends Api { yield* proxyApi.flutterMethods.map((Method method) => (method, proxyApi)); } if (superClass != null) { - final Set interfaceApisFromSuperClasses = - superClass!.associatedProxyApi!._recursiveFindAllInterfaceApis(); + final Set interfaceApisFromSuperClasses = superClass! + .associatedProxyApi! + ._recursiveFindAllInterfaceApis(); for (final AstProxyApi proxyApi in interfaceApisFromSuperClasses) { yield* proxyApi.methods.map((Method method) => (method, proxyApi)); } @@ -394,8 +397,9 @@ class Constructor extends Method { @override String toString() { - final String swiftFunctionStr = - swiftFunction.isEmpty ? '' : ' swiftFunction:$swiftFunction'; + final String swiftFunctionStr = swiftFunction.isEmpty + ? '' + : ' swiftFunction:$swiftFunction'; return '(Constructor name:$name parameters:$parameters $swiftFunctionStr documentationComments:$documentationComments)'; } } @@ -595,8 +599,9 @@ class TypeDeclaration { @override String toString() { - final String typeArgumentsStr = - typeArguments.isEmpty ? '' : ' typeArguments:$typeArguments'; + final String typeArgumentsStr = typeArguments.isEmpty + ? '' + : ' typeArguments:$typeArguments'; return '(TypeDeclaration baseName:$baseName isNullable:$isNullable$typeArgumentsStr isEnum:$isEnum isClass:$isClass isProxyApi:$isProxyApi)'; } } diff --git a/packages/pigeon/lib/src/cpp/cpp_generator.dart b/packages/pigeon/lib/src/cpp/cpp_generator.dart index 2ae403cfcd6..78f6eb263ee 100644 --- a/packages/pigeon/lib/src/cpp/cpp_generator.dart +++ b/packages/pigeon/lib/src/cpp/cpp_generator.dart @@ -465,10 +465,9 @@ class CppHeaderGenerator extends StructuredGenerator { _writeFunctionDeclaration( indent, 'FromEncodableList', - returnType: - isOverflowClass - ? 'flutter::EncodableValue' - : classDefinition.name, + returnType: isOverflowClass + ? 'flutter::EncodableValue' + : classDefinition.name, parameters: ['const flutter::EncodableList& list'], isStatic: true, ); @@ -814,14 +813,13 @@ class CppHeaderGenerator extends StructuredGenerator { Iterable params, String docComment, ) { - final List paramStrings = - params.map((NamedType param) { - final HostDatatype hostDatatype = getFieldHostDatatype( - param, - _baseCppTypeForBuiltinDartType, - ); - return '${_hostApiArgumentType(hostDatatype)} ${_makeVariableName(param)}'; - }).toList(); + final List paramStrings = params.map((NamedType param) { + final HostDatatype hostDatatype = getFieldHostDatatype( + param, + _baseCppTypeForBuiltinDartType, + ); + return '${_hostApiArgumentType(hostDatatype)} ${_makeVariableName(param)}'; + }).toList(); indent.writeln('$_commentPrefix $docComment'); _writeFunctionDeclaration( indent, @@ -1270,8 +1268,10 @@ EncodableValue $_overflowClassName::FromEncodableList( Indent indent, { required String dartPackageName, }) { - final List enumeratedTypes = - getEnumeratedTypes(root, excludeSealedClasses: true).toList(); + final List enumeratedTypes = getEnumeratedTypes( + root, + excludeSealedClasses: true, + ).toList(); indent.newln(); if (root.requiresOverflowClass) { _writeCodecOverflowUtilities( @@ -1342,16 +1342,16 @@ EncodableValue $_overflowClassName::FromEncodableList( for (final EnumeratedType customType in enumeratedTypes) { final String encodeString = customType.type == CustomTypes.customClass - ? 'std::any_cast<${customType.name}>(*custom_value).ToEncodableList()' - : 'static_cast(std::any_cast<${customType.name}>(*custom_value))'; + ? 'std::any_cast<${customType.name}>(*custom_value).ToEncodableList()' + : 'static_cast(std::any_cast<${customType.name}>(*custom_value))'; final String valueString = customType.enumeration < maximumCodecFieldKey - ? encodeString - : 'wrap.ToEncodableList()'; + ? encodeString + : 'wrap.ToEncodableList()'; final int enumeration = customType.enumeration < maximumCodecFieldKey - ? customType.enumeration - : maximumCodecFieldKey; + ? customType.enumeration + : maximumCodecFieldKey; indent.write( 'if (custom_value->type() == typeid(${customType.name})) ', ); @@ -1643,8 +1643,8 @@ EncodableValue $_overflowClassName::FromEncodableList( ); final String unwrapEnum = arg.type.isEnum && arg.type.isNullable - ? ' ? &(*$argName) : nullptr' - : ''; + ? ' ? &(*$argName) : nullptr' + : ''; methodArgument.add('$argName$unwrapEnum'); }); } @@ -1740,20 +1740,18 @@ return EncodableValue(EncodableList{ ); }); - final List paramStrings = - hostParams - .map( - (_HostNamedType param) => - '${_hostApiArgumentType(param.hostType)} ${param.name}', - ) - .toList(); - final List initializerStrings = - hostParams - .map( - (_HostNamedType param) => - '${param.name}_(${_fieldValueExpression(param.hostType, param.name)})', - ) - .toList(); + final List paramStrings = hostParams + .map( + (_HostNamedType param) => + '${_hostApiArgumentType(param.hostType)} ${param.name}', + ) + .toList(); + final List initializerStrings = hostParams + .map( + (_HostNamedType param) => + '${param.name}_(${_fieldValueExpression(param.hostType, param.name)})', + ) + .toList(); _writeFunctionDefinition( indent, classDefinition.name, @@ -1769,15 +1767,14 @@ return EncodableValue(EncodableList{ Class classDefinition, Iterable fields, ) { - final List initializerStrings = - fields.map((NamedType param) { - final String fieldName = _makeInstanceVariableName(param); - final HostDatatype hostType = getFieldHostDatatype( - param, - _shortBaseCppTypeForBuiltinDartType, - ); - return '$fieldName(${_fieldValueExpression(hostType, 'other.$fieldName', sourceIsField: true)})'; - }).toList(); + final List initializerStrings = fields.map((NamedType param) { + final String fieldName = _makeInstanceVariableName(param); + final HostDatatype hostType = getFieldHostDatatype( + param, + _shortBaseCppTypeForBuiltinDartType, + ); + return '$fieldName(${_fieldValueExpression(hostType, 'other.$fieldName', sourceIsField: true)})'; + }).toList(); _writeFunctionDefinition( indent, classDefinition.name, @@ -1812,10 +1809,9 @@ return EncodableValue(EncodableList{ if (_isPointerField(hostDatatype)) { final String constructor = 'std::make_unique<${hostDatatype.datatype}>(*$otherIvar)'; - valueExpression = - hostDatatype.isNullable - ? '$otherIvar ? $constructor : nullptr' - : constructor; + valueExpression = hostDatatype.isNullable + ? '$otherIvar ? $constructor : nullptr' + : constructor; } else { valueExpression = otherIvar; } @@ -1842,10 +1838,9 @@ return EncodableValue(EncodableList{ final String returnExpression; if (_isPointerField(hostDatatype)) { // Convert std::unique_ptr to either T* or const T&. - returnExpression = - hostDatatype.isNullable - ? '$instanceVariableName.get()' - : '*$instanceVariableName'; + returnExpression = hostDatatype.isNullable + ? '$instanceVariableName.get()' + : '*$instanceVariableName'; } else if (hostDatatype.isNullable) { // Convert std::optional to T*. returnExpression = @@ -1940,12 +1935,14 @@ return EncodableValue(EncodableList{ ); const String extractedValue = 'std::move(output).TakeValue()'; - final String wrapperType = - hostType.isBuiltin ? 'EncodableValue' : 'CustomEncodableValue'; + final String wrapperType = hostType.isBuiltin + ? 'EncodableValue' + : 'CustomEncodableValue'; if (returnType.isNullable) { // The value is a std::optional, so needs an extra layer of // handling. - nonErrorPath = ''' + nonErrorPath = + ''' ${prefix}auto output_optional = $extractedValue; ${prefix}if (output_optional) { $prefix\twrapped.push_back($wrapperType(std::move(output_optional).value())); @@ -1998,8 +1995,8 @@ ${prefix}reply(EncodableValue(std::move(wrapped)));'''; if (!hostType.isBuiltin) { final String nonNullValue = hostType.isNullable || (!hostType.isEnum && isNestedClass) - ? '*$variableName' - : variableName; + ? '*$variableName' + : variableName; encodableValue = 'CustomEncodableValue($nonNullValue)'; } else if (dartType.baseName == 'Object') { final String operator = hostType.isNullable ? '*' : ''; diff --git a/packages/pigeon/lib/src/dart/dart_generator.dart b/packages/pigeon/lib/src/dart/dart_generator.dart index 231f38384fa..a429c9e4cc3 100644 --- a/packages/pigeon/lib/src/dart/dart_generator.dart +++ b/packages/pigeon/lib/src/dart/dart_generator.dart @@ -212,10 +212,9 @@ class DartGenerator extends StructuredGenerator { docCommentSpec, ); final String sealed = classDefinition.isSealed ? 'sealed ' : ''; - final String implements = - classDefinition.superClassName != null - ? 'extends ${classDefinition.superClassName} ' - : ''; + final String implements = classDefinition.superClassName != null + ? 'extends ${classDefinition.superClassName} ' + : ''; indent.write('${sealed}class ${classDefinition.name} $implements'); indent.addScoped('{', '}', () { @@ -273,10 +272,11 @@ class DartGenerator extends StructuredGenerator { )) { final String required = !field.type.isNullable && field.defaultValue == null - ? 'required ' - : ''; - final String defaultValueString = - field.defaultValue == null ? '' : ' = ${field.defaultValue}'; + ? 'required ' + : ''; + final String defaultValueString = field.defaultValue == null + ? '' + : ' = ${field.defaultValue}'; indent.writeln('${required}this.${field.name}$defaultValueString,'); } }); @@ -326,10 +326,9 @@ class DartGenerator extends StructuredGenerator { indent.add('($resultAt as $genericType?)$castCallPrefix$castCall'); } else { final String castCallForcePrefix = field.type.isNullable ? '' : '!'; - final String castString = - field.type.baseName == 'Object' - ? '' - : ' as $genericType$nullableTag'; + final String castString = field.type.baseName == 'Object' + ? '' + : ' as $genericType$nullableTag'; indent.add('$resultAt$castCallForcePrefix$castString'); } @@ -404,10 +403,9 @@ class DartGenerator extends StructuredGenerator { indent.writeln('writeValue(buffer, value.index);'); } } else { - final String encodeString = - customType.type == CustomTypes.customClass - ? '.encode()' - : '.index'; + final String encodeString = customType.type == CustomTypes.customClass + ? '.encode()' + : '.index'; indent.writeln( 'final $_overflowClassName wrap = $_overflowClassName(type: ${customType.offset(nonSerializedClassCount) - maximumCodecFieldKey}, wrapped: value$encodeString);', ); @@ -451,8 +449,10 @@ class DartGenerator extends StructuredGenerator { ); indent.newln(); - final List enumeratedTypes = - getEnumeratedTypes(root, excludeSealedClasses: true).toList(); + final List enumeratedTypes = getEnumeratedTypes( + root, + excludeSealedClasses: true, + ).toList(); if (root.requiresOverflowClass) { _writeCodecOverflowUtilities(indent, enumeratedTypes); } @@ -556,10 +556,9 @@ class DartGenerator extends StructuredGenerator { ); final bool isAsync = func.isAsynchronous; - final String returnType = - isAsync - ? 'Future<${addGenericTypesNullable(func.returnType)}>' - : addGenericTypesNullable(func.returnType); + final String returnType = isAsync + ? 'Future<${addGenericTypesNullable(func.returnType)}>' + : addGenericTypesNullable(func.returnType); final String argSignature = _getMethodParameterSignature( func.parameters, ); @@ -581,10 +580,9 @@ class DartGenerator extends StructuredGenerator { parameters: func.parameters, returnType: func.returnType, addSuffixVariable: true, - channelName: - channelNameFunc == null - ? makeChannelName(api, func, dartPackageName) - : channelNameFunc(func), + channelName: channelNameFunc == null + ? makeChannelName(api, func, dartPackageName) + : channelNameFunc(func), isMockHandler: isMockHandler, isAsynchronous: func.isAsynchronous, ); @@ -710,178 +708,173 @@ final BinaryMessenger? ${varNamePrefix}binaryMessenger; required String dartPackageName, }) { final cb.Parameter binaryMessengerParameter = cb.Parameter( - (cb.ParameterBuilder builder) => - builder - ..name = 'binaryMessenger' - ..type = cb.refer('BinaryMessenger?') - ..named = true, + (cb.ParameterBuilder builder) => builder + ..name = 'binaryMessenger' + ..type = cb.refer('BinaryMessenger?') + ..named = true, ); final cb.Field binaryMessengerField = cb.Field( - (cb.FieldBuilder builder) => - builder - ..name = '${varNamePrefix}binaryMessenger' - ..type = cb.refer('BinaryMessenger?') - ..modifier = cb.FieldModifier.final$, + (cb.FieldBuilder builder) => builder + ..name = '${varNamePrefix}binaryMessenger' + ..type = cb.refer('BinaryMessenger?') + ..modifier = cb.FieldModifier.final$, ); final cb.Class instanceManagerApi = cb.Class( - (cb.ClassBuilder builder) => - builder - ..name = dartInstanceManagerApiClassName - ..docs.add( - '/// Generated API for managing the Dart and native `$dartInstanceManagerClassName`s.', - ) - ..constructors.add( - cb.Constructor((cb.ConstructorBuilder builder) { - builder - ..docs.add( - '/// Constructor for [$dartInstanceManagerApiClassName].', - ) - ..optionalParameters.add(binaryMessengerParameter) - ..initializers.add( - cb.Code( - '${binaryMessengerField.name} = ${binaryMessengerParameter.name}', - ), - ); - }), - ) - ..fields.addAll([ - binaryMessengerField, - cb.Field((cb.FieldBuilder builder) { - builder - ..name = pigeonChannelCodec - ..type = cb.refer('MessageCodec') - ..static = true - ..modifier = cb.FieldModifier.constant - ..assignment = const cb.Code('$_pigeonMessageCodec()'); - }), - ]) - ..methods.add( - cb.Method((cb.MethodBuilder builder) { - builder - ..name = 'setUpMessageHandlers' - ..static = true - ..returns = cb.refer('void') - ..optionalParameters.addAll([ - cb.Parameter( - (cb.ParameterBuilder builder) => - builder - ..name = '${classMemberNamePrefix}clearHandlers' - ..type = cb.refer('bool') - ..named = true - ..defaultTo = const cb.Code('false'), - ), - binaryMessengerParameter, - cb.Parameter( - (cb.ParameterBuilder builder) => - builder - ..name = 'instanceManager' - ..named = true - ..type = cb.refer('$dartInstanceManagerClassName?'), - ), - ]) - ..body = cb.Block.of( - cb.Block((cb.BlockBuilder builder) { - final StringBuffer messageHandlerSink = StringBuffer(); - writeFlutterMethodMessageHandler( - Indent(messageHandlerSink), - name: 'removeStrongReferenceName', - parameters: [ - Parameter( - name: 'identifier', - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), - ), - ], - returnType: const TypeDeclaration.voidDeclaration(), - channelName: makeRemoveStrongReferenceChannelName( - dartPackageName, + (cb.ClassBuilder builder) => builder + ..name = dartInstanceManagerApiClassName + ..docs.add( + '/// Generated API for managing the Dart and native `$dartInstanceManagerClassName`s.', + ) + ..constructors.add( + cb.Constructor((cb.ConstructorBuilder builder) { + builder + ..docs.add( + '/// Constructor for [$dartInstanceManagerApiClassName].', + ) + ..optionalParameters.add(binaryMessengerParameter) + ..initializers.add( + cb.Code( + '${binaryMessengerField.name} = ${binaryMessengerParameter.name}', + ), + ); + }), + ) + ..fields.addAll([ + binaryMessengerField, + cb.Field((cb.FieldBuilder builder) { + builder + ..name = pigeonChannelCodec + ..type = cb.refer('MessageCodec') + ..static = true + ..modifier = cb.FieldModifier.constant + ..assignment = const cb.Code('$_pigeonMessageCodec()'); + }), + ]) + ..methods.add( + cb.Method((cb.MethodBuilder builder) { + builder + ..name = 'setUpMessageHandlers' + ..static = true + ..returns = cb.refer('void') + ..optionalParameters.addAll([ + cb.Parameter( + (cb.ParameterBuilder builder) => builder + ..name = '${classMemberNamePrefix}clearHandlers' + ..type = cb.refer('bool') + ..named = true + ..defaultTo = const cb.Code('false'), + ), + binaryMessengerParameter, + cb.Parameter( + (cb.ParameterBuilder builder) => builder + ..name = 'instanceManager' + ..named = true + ..type = cb.refer('$dartInstanceManagerClassName?'), + ), + ]) + ..body = cb.Block.of( + cb.Block((cb.BlockBuilder builder) { + final StringBuffer messageHandlerSink = StringBuffer(); + writeFlutterMethodMessageHandler( + Indent(messageHandlerSink), + name: 'removeStrongReferenceName', + parameters: [ + Parameter( + name: 'identifier', + type: const TypeDeclaration( + baseName: 'int', + isNullable: false, ), - isMockHandler: false, - isAsynchronous: false, - nullHandlerExpression: - '${classMemberNamePrefix}clearHandlers', - onCreateApiCall: ( + ), + ], + returnType: const TypeDeclaration.voidDeclaration(), + channelName: makeRemoveStrongReferenceChannelName( + dartPackageName, + ), + isMockHandler: false, + isAsynchronous: false, + nullHandlerExpression: + '${classMemberNamePrefix}clearHandlers', + onCreateApiCall: + ( String methodName, Iterable parameters, Iterable safeArgumentNames, ) { return '(instanceManager ?? $dartInstanceManagerClassName.instance).remove(${safeArgumentNames.single})'; }, - ); - builder.statements.add( - cb.Code(messageHandlerSink.toString()), - ); - }).statements, ); - }), - ) - ..methods.addAll([ - cb.Method((cb.MethodBuilder builder) { - builder - ..name = 'removeStrongReference' - ..returns = cb.refer('Future') - ..modifier = cb.MethodModifier.async - ..requiredParameters.add( - cb.Parameter( - (cb.ParameterBuilder builder) => - builder - ..name = 'identifier' - ..type = cb.refer('int'), - ), - ) - ..body = cb.Block((cb.BlockBuilder builder) { - final StringBuffer messageCallSink = StringBuffer(); - writeHostMethodMessageCall( - Indent(messageCallSink), - addSuffixVariable: false, - channelName: makeRemoveStrongReferenceChannelName( - dartPackageName, + builder.statements.add( + cb.Code(messageHandlerSink.toString()), + ); + }).statements, + ); + }), + ) + ..methods.addAll([ + cb.Method((cb.MethodBuilder builder) { + builder + ..name = 'removeStrongReference' + ..returns = cb.refer('Future') + ..modifier = cb.MethodModifier.async + ..requiredParameters.add( + cb.Parameter( + (cb.ParameterBuilder builder) => builder + ..name = 'identifier' + ..type = cb.refer('int'), + ), + ) + ..body = cb.Block((cb.BlockBuilder builder) { + final StringBuffer messageCallSink = StringBuffer(); + writeHostMethodMessageCall( + Indent(messageCallSink), + addSuffixVariable: false, + channelName: makeRemoveStrongReferenceChannelName( + dartPackageName, + ), + parameters: [ + Parameter( + name: 'identifier', + type: const TypeDeclaration( + baseName: 'int', + isNullable: false, ), - parameters: [ - Parameter( - name: 'identifier', - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), - ), - ], - returnType: const TypeDeclaration.voidDeclaration(), - ); - builder.statements.addAll([ - cb.Code(messageCallSink.toString()), - ]); - }); - }), - cb.Method((cb.MethodBuilder builder) { - builder - ..name = 'clear' - ..returns = cb.refer('Future') - ..modifier = cb.MethodModifier.async - ..docs.addAll([ - '/// Clear the native `$dartInstanceManagerClassName`.', - '///', - '/// This is typically called after a hot restart.', - ]) - ..body = cb.Block((cb.BlockBuilder builder) { - final StringBuffer messageCallSink = StringBuffer(); - writeHostMethodMessageCall( - Indent(messageCallSink), - addSuffixVariable: false, - channelName: makeClearChannelName(dartPackageName), - parameters: [], - returnType: const TypeDeclaration.voidDeclaration(), - ); - builder.statements.addAll([ - cb.Code(messageCallSink.toString()), - ]); - }); - }), - ]), + ), + ], + returnType: const TypeDeclaration.voidDeclaration(), + ); + builder.statements.addAll([ + cb.Code(messageCallSink.toString()), + ]); + }); + }), + cb.Method((cb.MethodBuilder builder) { + builder + ..name = 'clear' + ..returns = cb.refer('Future') + ..modifier = cb.MethodModifier.async + ..docs.addAll([ + '/// Clear the native `$dartInstanceManagerClassName`.', + '///', + '/// This is typically called after a hot restart.', + ]) + ..body = cb.Block((cb.BlockBuilder builder) { + final StringBuffer messageCallSink = StringBuffer(); + writeHostMethodMessageCall( + Indent(messageCallSink), + addSuffixVariable: false, + channelName: makeClearChannelName(dartPackageName), + parameters: [], + returnType: const TypeDeclaration.voidDeclaration(), + ); + builder.statements.addAll([ + cb.Code(messageCallSink.toString()), + ]); + }); + }), + ]), ); final cb.DartEmitter emitter = cb.DartEmitter(useNullSafetySyntax: true); @@ -917,119 +910,110 @@ final BinaryMessenger? ${varNamePrefix}binaryMessenger; // AST class used by code_builder to generate the code. final cb.Class proxyApi = cb.Class( - (cb.ClassBuilder builder) => - builder - ..name = api.name - ..extend = - api.superClass != null - ? cb.refer(api.superClass!.baseName) - : cb.refer(proxyApiBaseClassName) - ..implements.addAll( - api.interfaces.map( - (TypeDeclaration type) => cb.refer(type.baseName), - ), - ) - ..docs.addAll( - asDocumentationComments( - api.documentationComments, - docCommentSpec, - ), - ) - ..constructors.addAll( - proxy_api_helper.constructors( - api.constructors, - apiName: api.name, - dartPackageName: dartPackageName, - codecName: codecName, - codecInstanceName: codecInstanceName, - superClassApi: api.superClass?.associatedProxyApi, - unattachedFields: api.unattachedFields, - flutterMethodsFromSuperClasses: - api.flutterMethodsFromSuperClassesWithApis(), - flutterMethodsFromInterfaces: - api.flutterMethodsFromInterfacesWithApis(), - declaredFlutterMethods: api.flutterMethods, - ), - ) - ..constructors.add( - proxy_api_helper.detachedConstructor( - apiName: api.name, - superClassApi: api.superClass?.associatedProxyApi, - unattachedFields: api.unattachedFields, - flutterMethodsFromSuperClasses: - api.flutterMethodsFromSuperClassesWithApis(), - flutterMethodsFromInterfaces: - api.flutterMethodsFromInterfacesWithApis(), - declaredFlutterMethods: api.flutterMethods, - ), - ) - ..fields.addAll([ - if (api.constructors.isNotEmpty || - api.attachedFields.any((ApiField field) => !field.isStatic) || - api.hostMethods.isNotEmpty) - proxy_api_helper.codecInstanceField( - codecInstanceName: codecInstanceName, - codecName: codecName, - ), - ]) - ..fields.addAll( - proxy_api_helper.unattachedFields(api.unattachedFields), - ) - ..fields.addAll( - proxy_api_helper.flutterMethodFields( - api.flutterMethods, - apiName: api.name, - ), - ) - ..fields.addAll( - proxy_api_helper.interfaceApiFields(api.apisOfInterfaces()), - ) - ..fields.addAll(proxy_api_helper.attachedFields(api.attachedFields)) - ..methods.addAll( - proxy_api_helper.staticAttachedFieldsGetters( - api.attachedFields.where((ApiField field) => field.isStatic), - apiName: api.name, - ), - ) - ..methods.add( - proxy_api_helper.setUpMessageHandlerMethod( - flutterMethods: api.flutterMethods, - apiName: api.name, - dartPackageName: dartPackageName, - codecName: codecName, - unattachedFields: api.unattachedFields, - hasCallbackConstructor: api.hasCallbackConstructor(), - ), - ) - ..methods.addAll( - proxy_api_helper.attachedFieldMethods( - api.attachedFields, - apiName: api.name, - dartPackageName: dartPackageName, - codecInstanceName: codecInstanceName, - codecName: codecName, - ), - ) - ..methods.addAll( - proxy_api_helper.hostMethods( - api.hostMethods, - apiName: api.name, - dartPackageName: dartPackageName, - codecInstanceName: codecInstanceName, - codecName: codecName, - ), - ) - ..methods.add( - proxy_api_helper.copyMethod( - apiName: api.name, - unattachedFields: api.unattachedFields, - flutterMethodsFromSuperClasses: - api.flutterMethodsFromSuperClassesWithApis(), - flutterMethodsFromInterfaces: - api.flutterMethodsFromInterfacesWithApis(), - declaredFlutterMethods: api.flutterMethods, - ), + (cb.ClassBuilder builder) => builder + ..name = api.name + ..extend = api.superClass != null + ? cb.refer(api.superClass!.baseName) + : cb.refer(proxyApiBaseClassName) + ..implements.addAll( + api.interfaces.map((TypeDeclaration type) => cb.refer(type.baseName)), + ) + ..docs.addAll( + asDocumentationComments(api.documentationComments, docCommentSpec), + ) + ..constructors.addAll( + proxy_api_helper.constructors( + api.constructors, + apiName: api.name, + dartPackageName: dartPackageName, + codecName: codecName, + codecInstanceName: codecInstanceName, + superClassApi: api.superClass?.associatedProxyApi, + unattachedFields: api.unattachedFields, + flutterMethodsFromSuperClasses: api + .flutterMethodsFromSuperClassesWithApis(), + flutterMethodsFromInterfaces: api + .flutterMethodsFromInterfacesWithApis(), + declaredFlutterMethods: api.flutterMethods, + ), + ) + ..constructors.add( + proxy_api_helper.detachedConstructor( + apiName: api.name, + superClassApi: api.superClass?.associatedProxyApi, + unattachedFields: api.unattachedFields, + flutterMethodsFromSuperClasses: api + .flutterMethodsFromSuperClassesWithApis(), + flutterMethodsFromInterfaces: api + .flutterMethodsFromInterfacesWithApis(), + declaredFlutterMethods: api.flutterMethods, + ), + ) + ..fields.addAll([ + if (api.constructors.isNotEmpty || + api.attachedFields.any((ApiField field) => !field.isStatic) || + api.hostMethods.isNotEmpty) + proxy_api_helper.codecInstanceField( + codecInstanceName: codecInstanceName, + codecName: codecName, ), + ]) + ..fields.addAll(proxy_api_helper.unattachedFields(api.unattachedFields)) + ..fields.addAll( + proxy_api_helper.flutterMethodFields( + api.flutterMethods, + apiName: api.name, + ), + ) + ..fields.addAll( + proxy_api_helper.interfaceApiFields(api.apisOfInterfaces()), + ) + ..fields.addAll(proxy_api_helper.attachedFields(api.attachedFields)) + ..methods.addAll( + proxy_api_helper.staticAttachedFieldsGetters( + api.attachedFields.where((ApiField field) => field.isStatic), + apiName: api.name, + ), + ) + ..methods.add( + proxy_api_helper.setUpMessageHandlerMethod( + flutterMethods: api.flutterMethods, + apiName: api.name, + dartPackageName: dartPackageName, + codecName: codecName, + unattachedFields: api.unattachedFields, + hasCallbackConstructor: api.hasCallbackConstructor(), + ), + ) + ..methods.addAll( + proxy_api_helper.attachedFieldMethods( + api.attachedFields, + apiName: api.name, + dartPackageName: dartPackageName, + codecInstanceName: codecInstanceName, + codecName: codecName, + ), + ) + ..methods.addAll( + proxy_api_helper.hostMethods( + api.hostMethods, + apiName: api.name, + dartPackageName: dartPackageName, + codecInstanceName: codecInstanceName, + codecName: codecName, + ), + ) + ..methods.add( + proxy_api_helper.copyMethod( + apiName: api.name, + unattachedFields: api.unattachedFields, + flutterMethodsFromSuperClasses: api + .flutterMethodsFromSuperClassesWithApis(), + flutterMethodsFromInterfaces: api + .flutterMethodsFromInterfacesWithApis(), + declaredFlutterMethods: api.flutterMethods, + ), + ), ); final cb.DartEmitter emitter = cb.DartEmitter(useNullSafetySyntax: true); @@ -1052,12 +1036,11 @@ final BinaryMessenger? ${varNamePrefix}binaryMessenger; final String testOutPath = generatorOptions.testOut ?? ''; _writeTestPrologue(generatorOptions, root, indent); _writeTestImports(generatorOptions, root, indent); - final String relativeDartPath = path.Context( - style: path.Style.posix, - ).relative( - _posixify(sourceOutPath), - from: _posixify(path.dirname(testOutPath)), - ); + final String relativeDartPath = path.Context(style: path.Style.posix) + .relative( + _posixify(sourceOutPath), + from: _posixify(path.dirname(testOutPath)), + ); if (!relativeDartPath.contains('/lib/')) { // If we can't figure out the package name or the relative path doesn't // include a 'lib' directory, try relative path import which only works in @@ -1091,8 +1074,8 @@ final BinaryMessenger? ${varNamePrefix}binaryMessenger; root, indent, mockApi, - channelNameFunc: - (Method func) => makeChannelName(api, func, dartPackageName), + channelNameFunc: (Method func) => + makeChannelName(api, func, dartPackageName), isMockHandler: true, dartPackageName: dartPackageName, ); @@ -1321,12 +1304,12 @@ if (wrapped == null) { final String genericCastCall = _makeGenericCastCall(returnType); const String accessor = '${varNamePrefix}replyList[0]'; // Avoid warnings from pointlessly casting to `Object?`. - final String nullablyTypedAccessor = - returnTypeName == 'Object' - ? accessor - : '($accessor as $returnTypeName?)'; - final String nullHandler = - returnType.isNullable ? (genericCastCall.isEmpty ? '' : '?') : '!'; + final String nullablyTypedAccessor = returnTypeName == 'Object' + ? accessor + : '($accessor as $returnTypeName?)'; + final String nullHandler = returnType.isNullable + ? (genericCastCall.isEmpty ? '' : '?') + : '!'; String returnStatement = 'return'; if (!returnType.isVoid) { returnStatement = @@ -1404,15 +1387,15 @@ if (${varNamePrefix}replyList == null) { 'final BasicMessageChannel ${varNamePrefix}channel = BasicMessageChannel(', ); indent.nest(2, () { - final String channelSuffix = - addSuffixVariable ? r'$messageChannelSuffix' : ''; + final String channelSuffix = addSuffixVariable + ? r'$messageChannelSuffix' + : ''; indent.writeln("'$channelName$channelSuffix', $pigeonChannelCodec,"); indent.writeln('binaryMessenger: binaryMessenger);'); }); - final String messageHandlerSetterWithOpeningParentheses = - isMockHandler - ? '_testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler(${varNamePrefix}channel, ' - : '${varNamePrefix}channel.setMessageHandler('; + final String messageHandlerSetterWithOpeningParentheses = isMockHandler + ? '_testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler(${varNamePrefix}channel, ' + : '${varNamePrefix}channel.setMessageHandler('; indent.write('if ($nullHandlerExpression) '); indent.addScoped('{', '}', () { indent.writeln('${messageHandlerSetterWithOpeningParentheses}null);'); @@ -1483,10 +1466,9 @@ if (${varNamePrefix}replyList == null) { } const String returnExpression = 'output'; - final String returnStatement = - isMockHandler - ? 'return [$returnExpression];' - : 'return wrapResponse(result: $returnExpression);'; + final String returnStatement = isMockHandler + ? 'return [$returnExpression];' + : 'return wrapResponse(result: $returnExpression);'; indent.writeln(returnStatement); } }, addTrailingNewline: false); @@ -1560,24 +1542,24 @@ String _getMethodParameterSignature( return signature; } - final List requiredPositionalParams = - parameters - .where((Parameter p) => p.isPositional && !p.isOptional) - .toList(); - final List optionalPositionalParams = - parameters - .where((Parameter p) => p.isPositional && p.isOptional) - .toList(); - final List namedParams = - parameters.where((Parameter p) => !p.isPositional).toList(); + final List requiredPositionalParams = parameters + .where((Parameter p) => p.isPositional && !p.isOptional) + .toList(); + final List optionalPositionalParams = parameters + .where((Parameter p) => p.isPositional && p.isOptional) + .toList(); + final List namedParams = parameters + .where((Parameter p) => !p.isPositional) + .toList(); String getParameterString(Parameter p) { final String required = p.isRequired && !p.isPositional ? 'required ' : ''; final String type = addGenericTypesNullable(p.type); - final String defaultValue = - p.defaultValue == null ? '' : ' = ${p.defaultValue}'; + final String defaultValue = p.defaultValue == null + ? '' + : ' = ${p.defaultValue}'; return '$required$type ${p.name}$defaultValue'; } @@ -1597,21 +1579,22 @@ String _getMethodParameterSignature( } final String trailingComma = optionalPositionalParams.isNotEmpty || namedParams.isNotEmpty ? ',' : ''; - final String baseParams = - signature.isNotEmpty ? '$signature$trailingComma ' : ''; + final String baseParams = signature.isNotEmpty + ? '$signature$trailingComma ' + : ''; if (optionalPositionalParams.isNotEmpty) { final String trailingComma = requiredPositionalParams.length + optionalPositionalParams.length > 2 - ? ',' - : ''; + ? ',' + : ''; return '$baseParams[$optionalParameterString$trailingComma]'; } if (namedParams.isNotEmpty) { final String trailingComma = addTrailingComma || - requiredPositionalParams.length + namedParams.length > 2 - ? ', ' - : ''; + requiredPositionalParams.length + namedParams.length > 2 + ? ', ' + : ''; return '$baseParams{$namedParameterString$trailingComma}'; } return signature; @@ -1622,10 +1605,9 @@ String _getMethodParameterSignature( String _flattenTypeArguments(List args) { return args .map( - (TypeDeclaration arg) => - arg.typeArguments.isEmpty - ? '${arg.baseName}${arg.isNullable ? '?' : ''}' - : '${arg.baseName}<${_flattenTypeArguments(arg.typeArguments)}>${arg.isNullable ? '?' : ''}', + (TypeDeclaration arg) => arg.typeArguments.isEmpty + ? '${arg.baseName}${arg.isNullable ? '?' : ''}' + : '${arg.baseName}<${_flattenTypeArguments(arg.typeArguments)}>${arg.isNullable ? '?' : ''}', ) .join(', '); } diff --git a/packages/pigeon/lib/src/dart/proxy_api_generator_helper.dart b/packages/pigeon/lib/src/dart/proxy_api_generator_helper.dart index f06d94d9b02..369a7913321 100644 --- a/packages/pigeon/lib/src/dart/proxy_api_generator_helper.dart +++ b/packages/pigeon/lib/src/dart/proxy_api_generator_helper.dart @@ -26,95 +26,83 @@ Iterable asConstructorParameters({ }) sync* { if (includeBinaryMessengerAndInstanceManager) { yield cb.Parameter( - (cb.ParameterBuilder builder) => - builder - ..name = '${classMemberNamePrefix}binaryMessenger' - ..named = true - ..type = defineType ? cb.refer('BinaryMessenger?') : null - ..toSuper = !defineType - ..required = false, + (cb.ParameterBuilder builder) => builder + ..name = '${classMemberNamePrefix}binaryMessenger' + ..named = true + ..type = defineType ? cb.refer('BinaryMessenger?') : null + ..toSuper = !defineType + ..required = false, ); yield cb.Parameter( - (cb.ParameterBuilder builder) => - builder - ..name = instanceManagerVarName - ..named = true - ..type = - defineType ? cb.refer('$dartInstanceManagerClassName?') : null - ..toSuper = !defineType - ..required = false, + (cb.ParameterBuilder builder) => builder + ..name = instanceManagerVarName + ..named = true + ..type = defineType ? cb.refer('$dartInstanceManagerClassName?') : null + ..toSuper = !defineType + ..required = false, ); } for (final ApiField field in unattachedFields) { yield cb.Parameter( - (cb.ParameterBuilder builder) => - builder - ..name = field.name - ..named = true - ..type = - defineType - ? cb.refer(addGenericTypesNullable(field.type)) - : null - ..toThis = !defineType - ..required = !field.type.isNullable, + (cb.ParameterBuilder builder) => builder + ..name = field.name + ..named = true + ..type = defineType + ? cb.refer(addGenericTypesNullable(field.type)) + : null + ..toThis = !defineType + ..required = !field.type.isNullable, ); } for (final (Method method, AstProxyApi api) in flutterMethodsFromSuperClasses) { yield cb.Parameter( - (cb.ParameterBuilder builder) => - builder - ..name = method.name - ..named = true - ..type = - defineType - ? methodAsFunctionType(method, apiName: api.name) - : null - ..toSuper = !defineType - ..required = method.isRequired, + (cb.ParameterBuilder builder) => builder + ..name = method.name + ..named = true + ..type = defineType + ? methodAsFunctionType(method, apiName: api.name) + : null + ..toSuper = !defineType + ..required = method.isRequired, ); } for (final (Method method, AstProxyApi api) in flutterMethodsFromInterfaces) { yield cb.Parameter( - (cb.ParameterBuilder builder) => - builder - ..name = method.name - ..named = true - ..type = - defineType - ? methodAsFunctionType(method, apiName: api.name) - : null - ..toThis = !defineType - ..required = method.isRequired, + (cb.ParameterBuilder builder) => builder + ..name = method.name + ..named = true + ..type = defineType + ? methodAsFunctionType(method, apiName: api.name) + : null + ..toThis = !defineType + ..required = method.isRequired, ); } for (final Method method in declaredFlutterMethods) { yield cb.Parameter( - (cb.ParameterBuilder builder) => - builder - ..name = method.name - ..named = true - ..type = - defineType - ? methodAsFunctionType(method, apiName: apiName) - : null - ..toThis = !defineType - ..required = method.isRequired, + (cb.ParameterBuilder builder) => builder + ..name = method.name + ..named = true + ..type = defineType + ? methodAsFunctionType(method, apiName: apiName) + : null + ..toThis = !defineType + ..required = method.isRequired, ); } yield* parameters.mapIndexed( (int index, NamedType parameter) => cb.Parameter( - (cb.ParameterBuilder builder) => - builder - ..name = getParameterName(index, parameter) - ..type = refer(parameter.type) - ..named = true - ..required = !parameter.type.isNullable, + (cb.ParameterBuilder builder) => builder + ..name = getParameterName(index, parameter) + ..type = refer(parameter.type) + ..named = true + ..required = !parameter.type.isNullable, ), ); } @@ -130,43 +118,42 @@ Iterable overridesClassConstructors( for (final Constructor constructor in api.constructors) { yield cb.Field((cb.FieldBuilder builder) { - final String constructorName = - constructor.name.isEmpty ? 'new' : constructor.name; + final String constructorName = constructor.name.isEmpty + ? 'new' + : constructor.name; final Iterable parameters = asConstructorParameters( apiName: api.name, parameters: constructor.parameters, unattachedFields: api.unattachedFields, - flutterMethodsFromSuperClasses: - api.flutterMethodsFromSuperClassesWithApis(), - flutterMethodsFromInterfaces: - api.flutterMethodsFromInterfacesWithApis(), + flutterMethodsFromSuperClasses: api + .flutterMethodsFromSuperClassesWithApis(), + flutterMethodsFromInterfaces: api + .flutterMethodsFromInterfacesWithApis(), declaredFlutterMethods: api.flutterMethods, includeBinaryMessengerAndInstanceManager: false, ); builder - ..name = - constructor.name.isEmpty - ? '${lowerCamelCaseApiName}_new' - : '${lowerCamelCaseApiName}_${constructor.name}' + ..name = constructor.name.isEmpty + ? '${lowerCamelCaseApiName}_new' + : '${lowerCamelCaseApiName}_${constructor.name}' ..static = true ..docs.add('/// Overrides [${api.name}.$constructorName].') ..type = cb.FunctionType( - (cb.FunctionTypeBuilder builder) => - builder - ..returnType = cb.refer(api.name) - ..isNullable = true - ..namedRequiredParameters.addAll({ - for (final cb.Parameter parameter in parameters.where( - (cb.Parameter parameter) => parameter.required, - )) - parameter.name: parameter.type!, - }) - ..namedParameters.addAll({ - for (final cb.Parameter parameter in parameters.where( - (cb.Parameter parameter) => !parameter.required, - )) - parameter.name: parameter.type!, - }), + (cb.FunctionTypeBuilder builder) => builder + ..returnType = cb.refer(api.name) + ..isNullable = true + ..namedRequiredParameters.addAll({ + for (final cb.Parameter parameter in parameters.where( + (cb.Parameter parameter) => parameter.required, + )) + parameter.name: parameter.type!, + }) + ..namedParameters.addAll({ + for (final cb.Parameter parameter in parameters.where( + (cb.Parameter parameter) => !parameter.required, + )) + parameter.name: parameter.type!, + }), ); }); } @@ -264,22 +251,18 @@ cb.Method overridesClassResetMethod(Iterable proxyApis) { /// positional arguments. cb.FunctionType methodAsFunctionType(Method method, {required String apiName}) { return cb.FunctionType( - (cb.FunctionTypeBuilder builder) => - builder - ..returnType = refer( - method.returnType, - asFuture: method.isAsynchronous, - ) - ..isNullable = !method.isRequired - ..requiredParameters.addAll([ - if (method.location == ApiLocation.flutter) - cb.refer('$apiName ${classMemberNamePrefix}instance'), - ...method.parameters.mapIndexed((int index, NamedType parameter) { - return cb.refer( - '${addGenericTypesNullable(parameter.type)} ${getParameterName(index, parameter)}', - ); - }), - ]), + (cb.FunctionTypeBuilder builder) => builder + ..returnType = refer(method.returnType, asFuture: method.isAsynchronous) + ..isNullable = !method.isRequired + ..requiredParameters.addAll([ + if (method.location == ApiLocation.flutter) + cb.refer('$apiName ${classMemberNamePrefix}instance'), + ...method.parameters.mapIndexed((int index, NamedType parameter) { + return cb.refer( + '${addGenericTypesNullable(parameter.type)} ${getParameterName(index, parameter)}', + ); + }), + ]), ); } @@ -300,22 +283,18 @@ Iterable staticAttachedFieldsGetters( }) sync* { for (final ApiField field in fields) { yield cb.Method( - (cb.MethodBuilder builder) => - builder - ..name = field.name - ..type = cb.MethodType.getter - ..static = true - ..returns = cb.refer(addGenericTypesNullable(field.type)) - ..docs.addAll( - asDocumentationComments( - field.documentationComments, - docCommentSpec, - ), - ) - ..lambda = true - ..body = cb.Code( - '$proxyApiOverridesClassName.${toLowerCamelCase(apiName)}_${field.name} ?? _${field.name}', - ), + (cb.MethodBuilder builder) => builder + ..name = field.name + ..type = cb.MethodType.getter + ..static = true + ..returns = cb.refer(addGenericTypesNullable(field.type)) + ..docs.addAll( + asDocumentationComments(field.documentationComments, docCommentSpec), + ) + ..lambda = true + ..body = cb.Code( + '$proxyApiOverridesClassName.${toLowerCamelCase(apiName)}_${field.name} ?? _${field.name}', + ), ); } } @@ -328,23 +307,22 @@ void writeProxyApiPigeonOverrides( required Iterable proxyApis, }) { final cb.Class proxyApiOverrides = cb.Class( - (cb.ClassBuilder builder) => - builder - ..name = proxyApiOverridesClassName - ..annotations.add(cb.refer('visibleForTesting')) - ..docs.addAll([ - '/// Provides overrides for the constructors and static members of each', - '/// Dart proxy class.', - '///', - '/// This is only intended to be used with unit tests to prevent errors from', - '/// making message calls in a unit test.', - '///', - '/// See [$proxyApiOverridesClassName.${classMemberNamePrefix}reset] to set all overrides back to null.', - ]) - ..fields.addAll(overridesClassConstructors(proxyApis)) - ..fields.addAll(overridesClassStaticFields(proxyApis)) - ..fields.addAll(overridesClassStaticMethods(proxyApis)) - ..methods.add(overridesClassResetMethod(proxyApis)), + (cb.ClassBuilder builder) => builder + ..name = proxyApiOverridesClassName + ..annotations.add(cb.refer('visibleForTesting')) + ..docs.addAll([ + '/// Provides overrides for the constructors and static members of each', + '/// Dart proxy class.', + '///', + '/// This is only intended to be used with unit tests to prevent errors from', + '/// making message calls in a unit test.', + '///', + '/// See [$proxyApiOverridesClassName.${classMemberNamePrefix}reset] to set all overrides back to null.', + ]) + ..fields.addAll(overridesClassConstructors(proxyApis)) + ..fields.addAll(overridesClassStaticFields(proxyApis)) + ..fields.addAll(overridesClassStaticMethods(proxyApis)) + ..methods.add(overridesClassResetMethod(proxyApis)), ); final cb.DartEmitter emitter = cb.DartEmitter(useNullSafetySyntax: true); @@ -368,22 +346,21 @@ Iterable constructors( required Iterable declaredFlutterMethods, }) sync* { final cb.Parameter binaryMessengerParameter = cb.Parameter( - (cb.ParameterBuilder builder) => - builder - ..name = '${classMemberNamePrefix}binaryMessenger' - ..named = true - ..toSuper = true, + (cb.ParameterBuilder builder) => builder + ..name = '${classMemberNamePrefix}binaryMessenger' + ..named = true + ..toSuper = true, ); for (final Constructor constructor in constructors) { - final String? factoryConstructorName = - constructor.name.isNotEmpty ? constructor.name : null; + final String? factoryConstructorName = constructor.name.isNotEmpty + ? constructor.name + : null; final String constructorName = '$classMemberNamePrefix${constructor.name.isNotEmpty ? constructor.name : 'new'}'; - final String overridesConstructorName = - constructor.name.isNotEmpty - ? '${toLowerCamelCase(apiName)}_${constructor.name}' - : '${toLowerCamelCase(apiName)}_new'; + final String overridesConstructorName = constructor.name.isNotEmpty + ? '${toLowerCamelCase(apiName)}_${constructor.name}' + : '${toLowerCamelCase(apiName)}_new'; // Factory constructor that forwards the parameters to the overrides class // or to the constructor yielded below this one. @@ -455,10 +432,9 @@ Iterable constructors( yield cb.Constructor((cb.ConstructorBuilder builder) { final String channelName = makeChannelNameWithStrings( apiName: apiName, - methodName: - constructor.name.isNotEmpty - ? constructor.name - : '${classMemberNamePrefix}defaultConstructor', + methodName: constructor.name.isNotEmpty + ? constructor.name + : '${classMemberNamePrefix}defaultConstructor', dartPackageName: dartPackageName, ); builder @@ -540,31 +516,30 @@ cb.Constructor detachedConstructor({ required Iterable declaredFlutterMethods, }) { return cb.Constructor( - (cb.ConstructorBuilder builder) => - builder - ..name = '${classMemberNamePrefix}detached' - ..docs.addAll([ - '/// Constructs [$apiName] without creating the associated native object.', - '///', - '/// This should only be used by subclasses created by this library or to', - '/// create copies for an [$dartInstanceManagerClassName].', - ]) - ..annotations.add(cb.refer('protected')) - ..optionalParameters.addAll( - asConstructorParameters( - apiName: apiName, - parameters: [], - unattachedFields: unattachedFields, - flutterMethodsFromSuperClasses: flutterMethodsFromSuperClasses, - flutterMethodsFromInterfaces: flutterMethodsFromInterfaces, - declaredFlutterMethods: declaredFlutterMethods, - defineType: false, - ), - ) - ..initializers.addAll([ - if (superClassApi != null) - const cb.Code('super.${classMemberNamePrefix}detached()'), - ]), + (cb.ConstructorBuilder builder) => builder + ..name = '${classMemberNamePrefix}detached' + ..docs.addAll([ + '/// Constructs [$apiName] without creating the associated native object.', + '///', + '/// This should only be used by subclasses created by this library or to', + '/// create copies for an [$dartInstanceManagerClassName].', + ]) + ..annotations.add(cb.refer('protected')) + ..optionalParameters.addAll( + asConstructorParameters( + apiName: apiName, + parameters: [], + unattachedFields: unattachedFields, + flutterMethodsFromSuperClasses: flutterMethodsFromSuperClasses, + flutterMethodsFromInterfaces: flutterMethodsFromInterfaces, + declaredFlutterMethods: declaredFlutterMethods, + defineType: false, + ), + ) + ..initializers.addAll([ + if (superClassApi != null) + const cb.Code('super.${classMemberNamePrefix}detached()'), + ]), ); } @@ -574,13 +549,12 @@ cb.Field codecInstanceField({ required String codecName, }) { return cb.Field( - (cb.FieldBuilder builder) => - builder - ..name = codecInstanceName - ..type = cb.refer(codecName) - ..late = true - ..modifier = cb.FieldModifier.final$ - ..assignment = cb.Code('$codecName($instanceManagerVarName)'), + (cb.FieldBuilder builder) => builder + ..name = codecInstanceName + ..type = cb.refer(codecName) + ..late = true + ..modifier = cb.FieldModifier.final$ + ..assignment = cb.Code('$codecName($instanceManagerVarName)'), ); } @@ -589,17 +563,13 @@ cb.Field codecInstanceField({ Iterable unattachedFields(Iterable fields) sync* { for (final ApiField field in fields) { yield cb.Field( - (cb.FieldBuilder builder) => - builder - ..name = field.name - ..type = cb.refer(addGenericTypesNullable(field.type)) - ..modifier = cb.FieldModifier.final$ - ..docs.addAll( - asDocumentationComments( - field.documentationComments, - docCommentSpec, - ), - ), + (cb.FieldBuilder builder) => builder + ..name = field.name + ..type = cb.refer(addGenericTypesNullable(field.type)) + ..modifier = cb.FieldModifier.final$ + ..docs.addAll( + asDocumentationComments(field.documentationComments, docCommentSpec), + ), ); } } @@ -615,37 +585,36 @@ Iterable flutterMethodFields( }) sync* { for (final Method method in methods) { yield cb.Field( - (cb.FieldBuilder builder) => - builder - ..name = method.name - ..modifier = cb.FieldModifier.final$ - ..docs.addAll( - asDocumentationComments([ - ...method.documentationComments, - ...[ - if (method.documentationComments.isEmpty) 'Callback method.', - '', - 'For the associated Native object to be automatically garbage collected,', - "it is required that the implementation of this `Function` doesn't have a", - 'strong reference to the encapsulating class instance. When this `Function`', - 'references a non-local variable, it is strongly recommended to access it', - 'with a `WeakReference`:', - '', - '```dart', - 'final WeakReference weakMyVariable = WeakReference(myVariable);', - 'final $apiName instance = $apiName(', - ' ${method.name}: ($apiName ${classMemberNamePrefix}instance, ...) {', - ' print(weakMyVariable?.target);', - ' },', - ');', - '```', - '', - 'Alternatively, [$dartInstanceManagerClassName.removeWeakReference] can be used to', - 'release the associated Native object manually.', - ], - ], docCommentSpec), - ) - ..type = methodAsFunctionType(method, apiName: apiName), + (cb.FieldBuilder builder) => builder + ..name = method.name + ..modifier = cb.FieldModifier.final$ + ..docs.addAll( + asDocumentationComments([ + ...method.documentationComments, + ...[ + if (method.documentationComments.isEmpty) 'Callback method.', + '', + 'For the associated Native object to be automatically garbage collected,', + "it is required that the implementation of this `Function` doesn't have a", + 'strong reference to the encapsulating class instance. When this `Function`', + 'references a non-local variable, it is strongly recommended to access it', + 'with a `WeakReference`:', + '', + '```dart', + 'final WeakReference weakMyVariable = WeakReference(myVariable);', + 'final $apiName instance = $apiName(', + ' ${method.name}: ($apiName ${classMemberNamePrefix}instance, ...) {', + ' print(weakMyVariable?.target);', + ' },', + ');', + '```', + '', + 'Alternatively, [$dartInstanceManagerClassName.removeWeakReference] can be used to', + 'release the associated Native object manually.', + ], + ], docCommentSpec), + ) + ..type = methodAsFunctionType(method, apiName: apiName), ); } } @@ -666,39 +635,35 @@ Iterable interfaceApiFields( for (final AstProxyApi proxyApi in apisOfInterfaces) { for (final Method method in proxyApi.methods) { yield cb.Field( - (cb.FieldBuilder builder) => - builder - ..name = method.name - ..modifier = cb.FieldModifier.final$ - ..annotations.add(cb.refer('override')) - ..docs.addAll( - asDocumentationComments( - method.documentationComments, - docCommentSpec, - ), + (cb.FieldBuilder builder) => builder + ..name = method.name + ..modifier = cb.FieldModifier.final$ + ..annotations.add(cb.refer('override')) + ..docs.addAll( + asDocumentationComments( + method.documentationComments, + docCommentSpec, + ), + ) + ..type = cb.FunctionType( + (cb.FunctionTypeBuilder builder) => builder + ..returnType = refer( + method.returnType, + asFuture: method.isAsynchronous, ) - ..type = cb.FunctionType( - (cb.FunctionTypeBuilder builder) => - builder - ..returnType = refer( - method.returnType, - asFuture: method.isAsynchronous, - ) - ..isNullable = !method.isRequired - ..requiredParameters.addAll([ - cb.refer( - '${proxyApi.name} ${classMemberNamePrefix}instance', - ), - ...method.parameters.mapIndexed(( - int index, - NamedType parameter, - ) { - return cb.refer( - '${addGenericTypesNullable(parameter.type)} ${getParameterName(index, parameter)}', - ); - }), - ]), - ), + ..isNullable = !method.isRequired + ..requiredParameters.addAll([ + cb.refer('${proxyApi.name} ${classMemberNamePrefix}instance'), + ...method.parameters.mapIndexed(( + int index, + NamedType parameter, + ) { + return cb.refer( + '${addGenericTypesNullable(parameter.type)} ${getParameterName(index, parameter)}', + ); + }), + ]), + ), ); } } @@ -717,20 +682,16 @@ Iterable interfaceApiFields( Iterable attachedFields(Iterable fields) sync* { for (final ApiField field in fields) { yield cb.Field( - (cb.FieldBuilder builder) => - builder - ..name = '${field.isStatic ? '_' : ''}${field.name}' - ..type = cb.refer(addGenericTypesNullable(field.type)) - ..modifier = cb.FieldModifier.final$ - ..static = field.isStatic - ..late = !field.isStatic - ..docs.addAll( - asDocumentationComments( - field.documentationComments, - docCommentSpec, - ), - ) - ..assignment = cb.Code('$varNamePrefix${field.name}()'), + (cb.FieldBuilder builder) => builder + ..name = '${field.isStatic ? '_' : ''}${field.name}' + ..type = cb.refer(addGenericTypesNullable(field.type)) + ..modifier = cb.FieldModifier.final$ + ..static = field.isStatic + ..late = !field.isStatic + ..docs.addAll( + asDocumentationComments(field.documentationComments, docCommentSpec), + ) + ..assignment = cb.Code('$varNamePrefix${field.name}()'), ); } } @@ -754,136 +715,123 @@ cb.Method setUpMessageHandlerMethod({ final bool hasAnyMessageHandlers = hasCallbackConstructor || flutterMethods.isNotEmpty; return cb.Method.returnsVoid( - (cb.MethodBuilder builder) => - builder - ..name = '${classMemberNamePrefix}setUpMessageHandlers' - ..returns = cb.refer('void') - ..static = true - ..optionalParameters.addAll([ - cb.Parameter( - (cb.ParameterBuilder builder) => - builder - ..name = '${classMemberNamePrefix}clearHandlers' - ..type = cb.refer('bool') - ..named = true - ..defaultTo = const cb.Code('false'), - ), - cb.Parameter( - (cb.ParameterBuilder builder) => - builder - ..name = '${classMemberNamePrefix}binaryMessenger' - ..named = true - ..type = cb.refer('BinaryMessenger?'), - ), - cb.Parameter( - (cb.ParameterBuilder builder) => - builder - ..name = instanceManagerVarName - ..named = true - ..type = cb.refer('$dartInstanceManagerClassName?'), - ), - if (hasCallbackConstructor) - cb.Parameter( - (cb.ParameterBuilder builder) => - builder - ..name = '${classMemberNamePrefix}newInstance' - ..named = true - ..type = cb.FunctionType( - (cb.FunctionTypeBuilder builder) => - builder - ..returnType = cb.refer(apiName) - ..isNullable = true - ..requiredParameters.addAll( - unattachedFields.mapIndexed(( - int index, - ApiField field, - ) { - return cb.refer( - '${addGenericTypesNullable(field.type)} ${getParameterName(index, field)}', - ); - }), - ), - ), - ), - for (final Method method in flutterMethods) - cb.Parameter( - (cb.ParameterBuilder builder) => - builder - ..name = method.name - ..type = cb.FunctionType( - (cb.FunctionTypeBuilder builder) => - builder - ..returnType = refer( - method.returnType, - asFuture: method.isAsynchronous, - ) - ..isNullable = true - ..requiredParameters.addAll([ - cb.refer( - '$apiName ${classMemberNamePrefix}instance', - ), - ...method.parameters.mapIndexed(( - int index, - NamedType parameter, - ) { - return cb.refer( - '${addGenericTypesNullable(parameter.type)} ${getParameterName(index, parameter)}', - ); - }), - ]), - ), - ), - ]) - ..body = cb.Block.of([ - if (hasAnyMessageHandlers) ...[ - cb.Code( - 'final $codecName $pigeonChannelCodec = $codecName($instanceManagerVarName ?? $dartInstanceManagerClassName.instance);', - ), - const cb.Code( - 'final BinaryMessenger? binaryMessenger = ${classMemberNamePrefix}binaryMessenger;', + (cb.MethodBuilder builder) => builder + ..name = '${classMemberNamePrefix}setUpMessageHandlers' + ..returns = cb.refer('void') + ..static = true + ..optionalParameters.addAll([ + cb.Parameter( + (cb.ParameterBuilder builder) => builder + ..name = '${classMemberNamePrefix}clearHandlers' + ..type = cb.refer('bool') + ..named = true + ..defaultTo = const cb.Code('false'), + ), + cb.Parameter( + (cb.ParameterBuilder builder) => builder + ..name = '${classMemberNamePrefix}binaryMessenger' + ..named = true + ..type = cb.refer('BinaryMessenger?'), + ), + cb.Parameter( + (cb.ParameterBuilder builder) => builder + ..name = instanceManagerVarName + ..named = true + ..type = cb.refer('$dartInstanceManagerClassName?'), + ), + if (hasCallbackConstructor) + cb.Parameter( + (cb.ParameterBuilder builder) => builder + ..name = '${classMemberNamePrefix}newInstance' + ..named = true + ..type = cb.FunctionType( + (cb.FunctionTypeBuilder builder) => builder + ..returnType = cb.refer(apiName) + ..isNullable = true + ..requiredParameters.addAll( + unattachedFields.mapIndexed((int index, ApiField field) { + return cb.refer( + '${addGenericTypesNullable(field.type)} ${getParameterName(index, field)}', + ); + }), + ), ), - ], - if (hasCallbackConstructor) - ...cb.Block((cb.BlockBuilder builder) { - final StringBuffer messageHandlerSink = StringBuffer(); - const String methodName = '${classMemberNamePrefix}newInstance'; - DartGenerator.writeFlutterMethodMessageHandler( - Indent(messageHandlerSink), - name: methodName, - parameters: [ - Parameter( - name: '${classMemberNamePrefix}instanceIdentifier', - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), - ), - ...unattachedFields.map((ApiField field) { - return Parameter(name: field.name, type: field.type); + ), + for (final Method method in flutterMethods) + cb.Parameter( + (cb.ParameterBuilder builder) => builder + ..name = method.name + ..type = cb.FunctionType( + (cb.FunctionTypeBuilder builder) => builder + ..returnType = refer( + method.returnType, + asFuture: method.isAsynchronous, + ) + ..isNullable = true + ..requiredParameters.addAll([ + cb.refer('$apiName ${classMemberNamePrefix}instance'), + ...method.parameters.mapIndexed(( + int index, + NamedType parameter, + ) { + return cb.refer( + '${addGenericTypesNullable(parameter.type)} ${getParameterName(index, parameter)}', + ); }), - ], - returnType: const TypeDeclaration.voidDeclaration(), - channelName: makeChannelNameWithStrings( - apiName: apiName, - methodName: methodName, - dartPackageName: dartPackageName, + ]), + ), + ), + ]) + ..body = cb.Block.of([ + if (hasAnyMessageHandlers) ...[ + cb.Code( + 'final $codecName $pigeonChannelCodec = $codecName($instanceManagerVarName ?? $dartInstanceManagerClassName.instance);', + ), + const cb.Code( + 'final BinaryMessenger? binaryMessenger = ${classMemberNamePrefix}binaryMessenger;', + ), + ], + if (hasCallbackConstructor) + ...cb.Block((cb.BlockBuilder builder) { + final StringBuffer messageHandlerSink = StringBuffer(); + const String methodName = '${classMemberNamePrefix}newInstance'; + DartGenerator.writeFlutterMethodMessageHandler( + Indent(messageHandlerSink), + name: methodName, + parameters: [ + Parameter( + name: '${classMemberNamePrefix}instanceIdentifier', + type: const TypeDeclaration( + baseName: 'int', + isNullable: false, ), - isMockHandler: false, - isAsynchronous: false, - nullHandlerExpression: - '${classMemberNamePrefix}clearHandlers', - onCreateApiCall: ( + ), + ...unattachedFields.map((ApiField field) { + return Parameter(name: field.name, type: field.type); + }), + ], + returnType: const TypeDeclaration.voidDeclaration(), + channelName: makeChannelNameWithStrings( + apiName: apiName, + methodName: methodName, + dartPackageName: dartPackageName, + ), + isMockHandler: false, + isAsynchronous: false, + nullHandlerExpression: '${classMemberNamePrefix}clearHandlers', + onCreateApiCall: + ( String methodName, Iterable parameters, Iterable safeArgumentNames, ) { - final String argsAsNamedParams = - map2(parameters, safeArgumentNames, ( - Parameter parameter, - String safeArgName, - ) { - return '${parameter.name}: $safeArgName,\n'; - }).skip(1).join(); + final String argsAsNamedParams = map2( + parameters, + safeArgumentNames, + (Parameter parameter, String safeArgName) { + return '${parameter.name}: $safeArgName,\n'; + }, + ).skip(1).join(); return '($instanceManagerVarName ?? $dartInstanceManagerClassName.instance)\n' ' .addHostCreatedInstance(\n' @@ -896,44 +844,40 @@ cb.Method setUpMessageHandlerMethod({ ' ${safeArgumentNames.first},\n' ')'; }, - ); - builder.statements.add(cb.Code(messageHandlerSink.toString())); - }).statements, - for (final Method method in flutterMethods) - ...cb.Block((cb.BlockBuilder builder) { - final StringBuffer messageHandlerSink = StringBuffer(); - DartGenerator.writeFlutterMethodMessageHandler( - Indent(messageHandlerSink), - name: method.name, - parameters: [ - Parameter( - name: '${classMemberNamePrefix}instance', - type: TypeDeclaration( - baseName: apiName, - isNullable: false, - ), - ), - ...method.parameters, - ], - returnType: TypeDeclaration( - baseName: method.returnType.baseName, - isNullable: - !method.isRequired || method.returnType.isNullable, - typeArguments: method.returnType.typeArguments, - associatedEnum: method.returnType.associatedEnum, - associatedClass: method.returnType.associatedClass, - associatedProxyApi: method.returnType.associatedProxyApi, - ), - channelName: makeChannelNameWithStrings( - apiName: apiName, - methodName: method.name, - dartPackageName: dartPackageName, - ), - isMockHandler: false, - isAsynchronous: method.isAsynchronous, - nullHandlerExpression: - '${classMemberNamePrefix}clearHandlers', - onCreateApiCall: ( + ); + builder.statements.add(cb.Code(messageHandlerSink.toString())); + }).statements, + for (final Method method in flutterMethods) + ...cb.Block((cb.BlockBuilder builder) { + final StringBuffer messageHandlerSink = StringBuffer(); + DartGenerator.writeFlutterMethodMessageHandler( + Indent(messageHandlerSink), + name: method.name, + parameters: [ + Parameter( + name: '${classMemberNamePrefix}instance', + type: TypeDeclaration(baseName: apiName, isNullable: false), + ), + ...method.parameters, + ], + returnType: TypeDeclaration( + baseName: method.returnType.baseName, + isNullable: !method.isRequired || method.returnType.isNullable, + typeArguments: method.returnType.typeArguments, + associatedEnum: method.returnType.associatedEnum, + associatedClass: method.returnType.associatedClass, + associatedProxyApi: method.returnType.associatedProxyApi, + ), + channelName: makeChannelNameWithStrings( + apiName: apiName, + methodName: method.name, + dartPackageName: dartPackageName, + ), + isMockHandler: false, + isAsynchronous: method.isAsynchronous, + nullHandlerExpression: '${classMemberNamePrefix}clearHandlers', + onCreateApiCall: + ( String methodName, Iterable parameters, Iterable safeArgumentNames, @@ -941,10 +885,10 @@ cb.Method setUpMessageHandlerMethod({ final String nullability = method.isRequired ? '' : '?'; return '($methodName ?? ${safeArgumentNames.first}.$methodName)$nullability.call(${safeArgumentNames.join(',')})'; }, - ); - builder.statements.add(cb.Code(messageHandlerSink.toString())); - }).statements, - ]), + ); + builder.statements.add(cb.Code(messageHandlerSink.toString())); + }).statements, + ]), ); } @@ -1050,100 +994,90 @@ Iterable hostMethods( assert(method.location == ApiLocation.host); final Iterable parameters = method.parameters.mapIndexed( (int index, NamedType parameter) => cb.Parameter( - (cb.ParameterBuilder builder) => - builder - ..name = getParameterName(index, parameter) - ..type = cb.refer(addGenericTypesNullable(parameter.type)), + (cb.ParameterBuilder builder) => builder + ..name = getParameterName(index, parameter) + ..type = cb.refer(addGenericTypesNullable(parameter.type)), ), ); yield cb.Method( - (cb.MethodBuilder builder) => - builder - ..name = method.name - ..static = method.isStatic - ..modifier = cb.MethodModifier.async - ..docs.addAll( - asDocumentationComments( - method.documentationComments, - docCommentSpec, - ), - ) - ..returns = refer(method.returnType, asFuture: true) - ..requiredParameters.addAll(parameters) - ..optionalParameters.addAll([ - if (method.isStatic) ...[ - cb.Parameter( - (cb.ParameterBuilder builder) => - builder - ..name = '${classMemberNamePrefix}binaryMessenger' - ..type = cb.refer('BinaryMessenger?') - ..named = true, - ), - cb.Parameter( - (cb.ParameterBuilder builder) => - builder - ..name = instanceManagerVarName - ..type = cb.refer('$dartInstanceManagerClassName?'), - ), - ], - ]) - ..body = cb.Block((cb.BlockBuilder builder) { - final StringBuffer messageCallSink = StringBuffer(); - DartGenerator.writeHostMethodMessageCall( - Indent(messageCallSink), - addSuffixVariable: false, - channelName: makeChannelNameWithStrings( - apiName: apiName, - methodName: method.name, - dartPackageName: dartPackageName, + (cb.MethodBuilder builder) => builder + ..name = method.name + ..static = method.isStatic + ..modifier = cb.MethodModifier.async + ..docs.addAll( + asDocumentationComments(method.documentationComments, docCommentSpec), + ) + ..returns = refer(method.returnType, asFuture: true) + ..requiredParameters.addAll(parameters) + ..optionalParameters.addAll([ + if (method.isStatic) ...[ + cb.Parameter( + (cb.ParameterBuilder builder) => builder + ..name = '${classMemberNamePrefix}binaryMessenger' + ..type = cb.refer('BinaryMessenger?') + ..named = true, + ), + cb.Parameter( + (cb.ParameterBuilder builder) => builder + ..name = instanceManagerVarName + ..type = cb.refer('$dartInstanceManagerClassName?'), + ), + ], + ]) + ..body = cb.Block((cb.BlockBuilder builder) { + final StringBuffer messageCallSink = StringBuffer(); + DartGenerator.writeHostMethodMessageCall( + Indent(messageCallSink), + addSuffixVariable: false, + channelName: makeChannelNameWithStrings( + apiName: apiName, + methodName: method.name, + dartPackageName: dartPackageName, + ), + parameters: [ + if (!method.isStatic) + Parameter( + name: 'this', + type: TypeDeclaration(baseName: apiName, isNullable: false), ), - parameters: [ - if (!method.isStatic) - Parameter( - name: 'this', - type: TypeDeclaration( - baseName: apiName, - isNullable: false, - ), + ...method.parameters, + ], + returnType: method.returnType, + ); + builder.statements.addAll([ + if (method.isStatic) ...[ + cb.Code( + 'if ($proxyApiOverridesClassName.${toLowerCamelCase(apiName)}_${method.name} != null) {', + ), + cb.CodeExpression( + cb.Code( + '$proxyApiOverridesClassName.${toLowerCamelCase(apiName)}_${method.name}!', ), - ...method.parameters, - ], - returnType: method.returnType, - ); - builder.statements.addAll([ - if (method.isStatic) ...[ - cb.Code( - 'if ($proxyApiOverridesClassName.${toLowerCamelCase(apiName)}_${method.name} != null) {', - ), - cb.CodeExpression( - cb.Code( - '$proxyApiOverridesClassName.${toLowerCamelCase(apiName)}_${method.name}!', - ), - ) - .call( - parameters.map( - (cb.Parameter parameter) => cb.refer(parameter.name), - ), - ) - .returned - .statement, - const cb.Code('}'), - ], - if (!method.isStatic) - cb.Code( - 'final $codecName $pigeonChannelCodec =\n' - ' $codecInstanceName;', ) - else - cb.Code( - 'final $codecName $pigeonChannelCodec = $codecName($instanceManagerVarName ?? $dartInstanceManagerClassName.instance);', - ), - const cb.Code( - 'final BinaryMessenger? ${varNamePrefix}binaryMessenger = ${classMemberNamePrefix}binaryMessenger;', - ), - cb.Code(messageCallSink.toString()), - ]); - }), + .call( + parameters.map( + (cb.Parameter parameter) => cb.refer(parameter.name), + ), + ) + .returned + .statement, + const cb.Code('}'), + ], + if (!method.isStatic) + cb.Code( + 'final $codecName $pigeonChannelCodec =\n' + ' $codecInstanceName;', + ) + else + cb.Code( + 'final $codecName $pigeonChannelCodec = $codecName($instanceManagerVarName ?? $dartInstanceManagerClassName.instance);', + ), + const cb.Code( + 'final BinaryMessenger? ${varNamePrefix}binaryMessenger = ${classMemberNamePrefix}binaryMessenger;', + ), + cb.Code(messageCallSink.toString()), + ]); + }), ); } } @@ -1169,20 +1103,19 @@ cb.Method copyMethod({ declaredFlutterMethods: declaredFlutterMethods, ); return cb.Method( - (cb.MethodBuilder builder) => - builder - ..name = '${classMemberNamePrefix}copy' - ..returns = cb.refer(apiName) - ..annotations.add(cb.refer('override')) - ..body = cb.Block.of([ - cb - .refer('$apiName.${classMemberNamePrefix}detached') - .call([], { - for (final cb.Parameter parameter in parameters) - parameter.name: cb.refer(parameter.name), - }) - .returned - .statement, - ]), + (cb.MethodBuilder builder) => builder + ..name = '${classMemberNamePrefix}copy' + ..returns = cb.refer(apiName) + ..annotations.add(cb.refer('override')) + ..body = cb.Block.of([ + cb + .refer('$apiName.${classMemberNamePrefix}detached') + .call([], { + for (final cb.Parameter parameter in parameters) + parameter.name: cb.refer(parameter.name), + }) + .returned + .statement, + ]), ); } diff --git a/packages/pigeon/lib/src/dart/templates.dart b/packages/pigeon/lib/src/dart/templates.dart index 4efbc2c56c4..9fb01a90b52 100644 --- a/packages/pigeon/lib/src/dart/templates.dart +++ b/packages/pigeon/lib/src/dart/templates.dart @@ -235,7 +235,8 @@ class $dartInstanceManagerClassName { /// The base class for all Dart proxy classes. /// /// All Dart proxy classes generated as a part of a ProxyApi extends this one. -const String proxyApiBaseClass = ''' +const String proxyApiBaseClass = + ''' /// An immutable object that serves as the base class for all Dart proxy classes /// and can provide functional copies of itself. /// @@ -277,7 +278,8 @@ abstract class $proxyApiBaseClassName { /// All generated Dart proxy classes should use this codec or extend it. This /// codec adds support to convert instances to their corresponding identifier /// from an `InstanceManager` and vice versa. -const String proxyApiBaseCodec = ''' +const String proxyApiBaseCodec = + ''' class $_proxyApiCodecName extends _PigeonCodec { const $_proxyApiCodecName(this.instanceManager); final $dartInstanceManagerClassName instanceManager; diff --git a/packages/pigeon/lib/src/generator_tools.dart b/packages/pigeon/lib/src/generator_tools.dart index 91032ee0b9c..73ced7b3134 100644 --- a/packages/pigeon/lib/src/generator_tools.dart +++ b/packages/pigeon/lib/src/generator_tools.dart @@ -83,19 +83,17 @@ class Indent { }) { final List lines = input.split('\n'); - final int indentationToRemove = - !trimIndentation - ? 0 - : lines - .where((String line) => line.trim().isNotEmpty) - .map((String line) => line.length - line.trimLeft().length) - .reduce(min); + final int indentationToRemove = !trimIndentation + ? 0 + : lines + .where((String line) => line.trim().isNotEmpty) + .map((String line) => line.length - line.trimLeft().length) + .reduce(min); for (int i = 0; i < lines.length; ++i) { - final String line = - lines[i].length >= indentationToRemove - ? lines[i].substring(indentationToRemove) - : lines[i]; + final String line = lines[i].length >= indentationToRemove + ? lines[i].substring(indentationToRemove) + : lines[i]; if (i == 0 && !leadingSpace) { add(line.replaceAll('\t', tab)); @@ -279,10 +277,9 @@ HostDatatype _getHostDatatype( final String? datatype = builtinResolver(type); if (datatype == null) { if (type.isClass) { - final String customName = - customResolver != null - ? customResolver(type.baseName) - : type.baseName; + final String customName = customResolver != null + ? customResolver(type.baseName) + : type.baseName; return HostDatatype( datatype: customName, isBuiltin: false, @@ -290,10 +287,9 @@ HostDatatype _getHostDatatype( isEnum: false, ); } else if (type.isEnum) { - final String customName = - customResolver != null - ? customResolver(type.baseName) - : type.baseName; + final String customName = customResolver != null + ? customResolver(type.baseName) + : type.baseName; return HostDatatype( datatype: customName, isBuiltin: false, @@ -328,8 +324,9 @@ const String generatedCodeWarning = /// Warning printed at the top of all generated code. String getGeneratedCodeWarning() { - final String versionString = - includeVersionInGeneratedWarning ? ' (v$pigeonVersion)' : ''; + final String versionString = includeVersionInGeneratedWarning + ? ' (v$pigeonVersion)' + : ''; return 'Autogenerated from Pigeon$versionString, do not edit directly.'; } @@ -567,8 +564,9 @@ Map> getReferencedTypes( } } - final Set referencedTypeNames = - references.map.keys.map((TypeDeclaration e) => e.baseName).toSet(); + final Set referencedTypeNames = references.map.keys + .map((TypeDeclaration e) => e.baseName) + .toSet(); final List classesToCheck = List.from(referencedTypeNames); while (classesToCheck.isNotEmpty) { final String next = classesToCheck.removeLast(); diff --git a/packages/pigeon/lib/src/gobject/gobject_generator.dart b/packages/pigeon/lib/src/gobject/gobject_generator.dart index c9db9fb809e..103a2b0f905 100644 --- a/packages/pigeon/lib/src/gobject/gobject_generator.dart +++ b/packages/pigeon/lib/src/gobject/gobject_generator.dart @@ -561,10 +561,9 @@ class GObjectHeaderGenerator else 'Returns: a return value.', ], _docCommentSpec); - final String returnType = - _isNullablePrimitiveType(method.returnType) - ? '$primitiveType*' - : primitiveType; + final String returnType = _isNullablePrimitiveType(method.returnType) + ? '$primitiveType*' + : primitiveType; indent.writeln( '$returnType ${responseMethodPrefix}_get_return_value($responseClassName* response${_isNumericListType(method.returnType) ? ', size_t* return_value_length' : ''});', ); @@ -715,8 +714,9 @@ class GObjectHeaderGenerator '${className}ResponseHandle* response_handle', 'gpointer user_data', ]); - final String returnType = - method.isAsynchronous ? 'void' : '$responseClassName*'; + final String returnType = method.isAsynchronous + ? 'void' + : '$responseClassName*'; indent.writeln("$returnType (*$methodName)(${methodArgs.join(', ')});"); } }); @@ -1089,10 +1089,9 @@ class GObjectSourceGenerator final String customTypeId = _getCustomTypeId(module, customType); indent.newln(); - final String valueType = - customType.type == CustomTypes.customClass - ? '$customTypeName*' - : 'FlValue*'; + final String valueType = customType.type == CustomTypes.customClass + ? '$customTypeName*' + : 'FlValue*'; indent.writeScoped( 'static gboolean ${codecMethodPrefix}_write_$snakeCustomTypeName($_standardCodecName* codec, GByteArray* buffer, $valueType value, GError** error) {', '}', @@ -1457,10 +1456,9 @@ class GObjectSourceGenerator ); indent.newln(); - final String returnType = - _isNullablePrimitiveType(method.returnType) - ? '$primitiveType*' - : primitiveType; + final String returnType = _isNullablePrimitiveType(method.returnType) + ? '$primitiveType*' + : primitiveType; indent.writeScoped( '$returnType ${responseMethodPrefix}_get_return_value($responseClassName* self${_isNumericListType(method.returnType) ? ', size_t* return_value_length' : ''}) {', '}', @@ -2442,20 +2440,17 @@ String _makeFlValue( } else if (type.baseName == 'void') { value = 'fl_value_new_null()'; } else if (type.baseName == 'bool') { - value = - type.isNullable - ? 'fl_value_new_bool(*$variableName)' - : 'fl_value_new_bool($variableName)'; + value = type.isNullable + ? 'fl_value_new_bool(*$variableName)' + : 'fl_value_new_bool($variableName)'; } else if (type.baseName == 'int') { - value = - type.isNullable - ? 'fl_value_new_int(*$variableName)' - : 'fl_value_new_int($variableName)'; + value = type.isNullable + ? 'fl_value_new_int(*$variableName)' + : 'fl_value_new_int($variableName)'; } else if (type.baseName == 'double') { - value = - type.isNullable - ? 'fl_value_new_float(*$variableName)' - : 'fl_value_new_float($variableName)'; + value = type.isNullable + ? 'fl_value_new_float(*$variableName)' + : 'fl_value_new_float($variableName)'; } else if (type.baseName == 'String') { value = 'fl_value_new_string($variableName)'; } else if (type.baseName == 'Uint8List') { diff --git a/packages/pigeon/lib/src/java/java_generator.dart b/packages/pigeon/lib/src/java/java_generator.dart index addbf487267..de675d73458 100644 --- a/packages/pigeon/lib/src/java/java_generator.dart +++ b/packages/pigeon/lib/src/java/java_generator.dart @@ -313,8 +313,9 @@ class JavaGenerator extends StructuredGenerator { field, (TypeDeclaration x) => _javaTypeForBuiltinDartType(x), ); - final String nullability = - field.type.isNullable ? '@Nullable ' : '@NonNull '; + final String nullability = field.type.isNullable + ? '@Nullable ' + : '@NonNull '; addDocumentationComments( indent, field.documentationComments, @@ -405,10 +406,9 @@ class JavaGenerator extends StructuredGenerator { final Iterable nonArrayFieldNames = classDefinition.fields .where((NamedType field) => !_javaTypeIsArray(field.type)) .map((NamedType field) => field.name); - final String nonArrayHashValue = - nonArrayFieldNames.isNotEmpty - ? 'Objects.hash(${nonArrayFieldNames.join(', ')})' - : '0'; + final String nonArrayHashValue = nonArrayFieldNames.isNotEmpty + ? 'Objects.hash(${nonArrayFieldNames.join(', ')})' + : '0'; if (arrayFieldNames.isEmpty) { // Return directly if there are no array variables, to avoid redundant @@ -444,8 +444,9 @@ class JavaGenerator extends StructuredGenerator { field, (TypeDeclaration x) => _javaTypeForBuiltinDartType(x), ); - final String nullability = - field.type.isNullable ? '@Nullable' : '@NonNull'; + final String nullability = field.type.isNullable + ? '@Nullable' + : '@NonNull'; indent.newln(); indent.writeln( 'private @Nullable ${hostDatatype.datatype} ${field.name};', @@ -543,24 +544,24 @@ class JavaGenerator extends StructuredGenerator { Indent indent, { required String dartPackageName, }) { - final List enumeratedTypes = - getEnumeratedTypes(root, excludeSealedClasses: true).toList(); + final List enumeratedTypes = getEnumeratedTypes( + root, + excludeSealedClasses: true, + ).toList(); void writeEncodeLogic(EnumeratedType customType) { - final String encodeString = - customType.type == CustomTypes.customClass ? 'toList()' : 'index'; - final String nullCheck = - customType.type == CustomTypes.customEnum - ? 'value == null ? null : ' - : ''; - final String valueString = - customType.enumeration < maximumCodecFieldKey - ? '$nullCheck((${customType.name}) value).$encodeString' - : 'wrap.toList()'; - final int enumeration = - customType.enumeration < maximumCodecFieldKey - ? customType.enumeration - : maximumCodecFieldKey; + final String encodeString = customType.type == CustomTypes.customClass + ? 'toList()' + : 'index'; + final String nullCheck = customType.type == CustomTypes.customEnum + ? 'value == null ? null : ' + : ''; + final String valueString = customType.enumeration < maximumCodecFieldKey + ? '$nullCheck((${customType.name}) value).$encodeString' + : 'wrap.toList()'; + final int enumeration = customType.enumeration < maximumCodecFieldKey + ? customType.enumeration + : maximumCodecFieldKey; indent.add('if (value instanceof ${customType.name}) '); indent.addScoped('{', '} else ', () { @@ -800,10 +801,9 @@ if (wrapped == null) { for (final Method func in api.methods) { final String resultType = _getResultType(func.returnType); - final String returnType = - func.returnType.isVoid - ? 'Void' - : _javaTypeForDartType(func.returnType); + final String returnType = func.returnType.isVoid + ? 'Void' + : _javaTypeForDartType(func.returnType); String sendArgument; addDocumentationComments( indent, @@ -1008,8 +1008,8 @@ if (wrapped == null) { dartPackageName: dartPackageName, serialBackgroundQueue: method.taskQueueType == TaskQueueType.serialBackgroundThread - ? serialBackgroundQueue - : null, + ? serialBackgroundQueue + : null, ); } }); @@ -1027,14 +1027,12 @@ if (wrapped == null) { final Method method, ) { final String resultType = _getResultType(method.returnType); - final String nullableType = - method.isAsynchronous - ? '' - : _nullabilityAnnotationFromType(method.returnType); - final String returnType = - method.isAsynchronous - ? 'void' - : _javaTypeForDartType(method.returnType); + final String nullableType = method.isAsynchronous + ? '' + : _nullabilityAnnotationFromType(method.returnType); + final String returnType = method.isAsynchronous + ? 'void' + : _javaTypeForDartType(method.returnType); final List argSignature = []; if (method.parameters.isNotEmpty) { final Iterable argTypes = method.parameters.map( @@ -1100,10 +1098,9 @@ if (wrapped == null) { indent.nest(2, () { indent.write('(message, reply) -> '); indent.addScoped('{', '});', () { - final String returnType = - method.returnType.isVoid - ? 'Void' - : _javaTypeForDartType(method.returnType); + final String returnType = method.returnType.isVoid + ? 'Void' + : _javaTypeForDartType(method.returnType); indent.writeln('ArrayList wrapped = new ArrayList<>();'); final List methodArgument = []; if (method.parameters.isNotEmpty) { @@ -1123,13 +1120,16 @@ if (wrapped == null) { }); } if (method.isAsynchronous) { - final String resultValue = - method.returnType.isVoid ? 'null' : 'result'; + final String resultValue = method.returnType.isVoid + ? 'null' + : 'result'; final String resultType = _getResultType(method.returnType); - final String resultParam = - method.returnType.isVoid ? '' : '$returnType result'; - final String addResultArg = - method.returnType.isVoid ? 'null' : resultValue; + final String resultParam = method.returnType.isVoid + ? '' + : '$returnType result'; + final String addResultArg = method.returnType.isVoid + ? 'null' + : resultValue; const String resultName = 'resultCallback'; indent.format(''' $resultType $resultName = diff --git a/packages/pigeon/lib/src/kotlin/kotlin_generator.dart b/packages/pigeon/lib/src/kotlin/kotlin_generator.dart index 3c3d27bc082..7745dd9e7aa 100644 --- a/packages/pigeon/lib/src/kotlin/kotlin_generator.dart +++ b/packages/pigeon/lib/src/kotlin/kotlin_generator.dart @@ -342,10 +342,9 @@ class KotlinGenerator extends StructuredGenerator { }) { final String privateString = private ? 'private ' : ''; final String classType = classDefinition.isSealed ? 'sealed' : 'data'; - final String inheritance = - classDefinition.superClass != null - ? ' : ${classDefinition.superClassName}()' - : ''; + final String inheritance = classDefinition.superClass != null + ? ' : ${classDefinition.superClassName}()' + : ''; indent.write('$privateString$classType class ${classDefinition.name} '); if (classDefinition.isSealed) { return; @@ -419,8 +418,8 @@ class KotlinGenerator extends StructuredGenerator { )) { final String comma = getFieldsInSerializationOrder(classDefinition).last == field - ? '' - : ', '; + ? '' + : ', '; indent.add('${field.name}$comma'); } indent.addln(')'); @@ -470,22 +469,21 @@ class KotlinGenerator extends StructuredGenerator { Indent indent, { required String dartPackageName, }) { - final List enumeratedTypes = - getEnumeratedTypes(root, excludeSealedClasses: true).toList(); + final List enumeratedTypes = getEnumeratedTypes( + root, + excludeSealedClasses: true, + ).toList(); void writeEncodeLogic(EnumeratedType customType) { - final String encodeString = - customType.type == CustomTypes.customClass - ? 'toList()' - : 'raw.toLong()'; - final String valueString = - customType.enumeration < maximumCodecFieldKey - ? 'value.$encodeString' - : 'wrap.toList()'; - final int enumeration = - customType.enumeration < maximumCodecFieldKey - ? customType.enumeration - : maximumCodecFieldKey; + final String encodeString = customType.type == CustomTypes.customClass + ? 'toList()' + : 'raw.toLong()'; + final String valueString = customType.enumeration < maximumCodecFieldKey + ? 'value.$encodeString' + : 'wrap.toList()'; + final int enumeration = customType.enumeration < maximumCodecFieldKey + ? customType.enumeration + : maximumCodecFieldKey; indent.writeScoped('is ${customType.name} -> {', '}', () { if (customType.enumeration >= maximumCodecFieldKey) { indent.writeln( @@ -703,26 +701,27 @@ if (wrapped == null) { channelName: makeChannelName(api, method, dartPackageName), documentationComments: method.documentationComments, dartPackageName: dartPackageName, - onWriteBody: ( - Indent indent, { - required InternalKotlinOptions generatorOptions, - required List parameters, - required TypeDeclaration returnType, - required String channelName, - required String errorClassName, - }) { - indent.writeln( - r'val separatedMessageChannelSuffix = if (messageChannelSuffix.isNotEmpty()) ".$messageChannelSuffix" else ""', - ); - _writeFlutterMethodMessageCall( - indent, - generatorOptions: generatorOptions, - parameters: parameters, - returnType: returnType, - channelName: '$channelName\$separatedMessageChannelSuffix', - errorClassName: errorClassName, - ); - }, + onWriteBody: + ( + Indent indent, { + required InternalKotlinOptions generatorOptions, + required List parameters, + required TypeDeclaration returnType, + required String channelName, + required String errorClassName, + }) { + indent.writeln( + r'val separatedMessageChannelSuffix = if (messageChannelSuffix.isNotEmpty()) ".$messageChannelSuffix" else ""', + ); + _writeFlutterMethodMessageCall( + indent, + generatorOptions: generatorOptions, + parameters: parameters, + returnType: returnType, + channelName: '$channelName\$separatedMessageChannelSuffix', + errorClassName: errorClassName, + ); + }, ); } }); @@ -814,8 +813,8 @@ if (wrapped == null) { isAsynchronous: method.isAsynchronous, serialBackgroundQueue: method.taskQueueType == TaskQueueType.serialBackgroundThread - ? serialBackgroundQueue - : null, + ? serialBackgroundQueue + : null, ); } }); @@ -890,12 +889,10 @@ if (wrapped == null) { ], returnType: const TypeDeclaration.voidDeclaration(), setHandlerCondition: setHandlerCondition, - onCreateCall: ( - List safeArgNames, { - required String apiVarName, - }) { - return 'instanceManager.remove(${safeArgNames.single})'; - }, + onCreateCall: + (List safeArgNames, {required String apiVarName}) { + return 'instanceManager.remove(${safeArgNames.single})'; + }, ); _writeHostMethodMessageHandler( indent, @@ -906,12 +903,10 @@ if (wrapped == null) { parameters: [], returnType: const TypeDeclaration.voidDeclaration(), setHandlerCondition: setHandlerCondition, - onCreateCall: ( - List safeArgNames, { - required String apiVarName, - }) { - return 'instanceManager.clear()'; - }, + onCreateCall: + (List safeArgNames, {required String apiVarName}) { + return 'instanceManager.clear()'; + }, ); }, ); @@ -942,8 +937,8 @@ if (wrapped == null) { Root root, Indent indent, ) { - final Iterable allProxyApis = - root.apis.whereType(); + final Iterable allProxyApis = root.apis + .whereType(); _writeProxyApiRegistrar( indent, @@ -1047,10 +1042,9 @@ if (wrapped == null) { api.kotlinOptions?.fullClassName ?? api.name; final int? minApi = api.kotlinOptions?.minAndroidApi; - final String versionCheck = - minApi != null - ? 'android.os.Build.VERSION.SDK_INT >= $minApi && ' - : ''; + final String versionCheck = minApi != null + ? 'android.os.Build.VERSION.SDK_INT >= $minApi && ' + : ''; indent.format(''' ${index > 0 ? ' else ' : ''}if (${versionCheck}value is $className) { @@ -1094,8 +1088,9 @@ if (wrapped == null) { ); indent.writeln('@Suppress("UNCHECKED_CAST")'); // The API only needs to be abstract if there are methods to override. - final String classModifier = - api.hasMethodsRequiringImplementation() ? 'abstract' : 'open'; + final String classModifier = api.hasMethodsRequiringImplementation() + ? 'abstract' + : 'open'; indent.writeScoped( '$classModifier class $kotlinApiName(open val pigeonRegistrar: ${proxyApiRegistrarName(generatorOptions)}) {', '}', @@ -1407,8 +1402,9 @@ fun deepEquals(a: Any?, b: Any?): Boolean { ); } - final String returnTypeString = - returnType.isVoid ? '' : _nullSafeKotlinTypeForDartType(returnType); + final String returnTypeString = returnType.isVoid + ? '' + : _nullSafeKotlinTypeForDartType(returnType); final String resultType = returnType.isVoid ? 'Unit' : returnTypeString; addDocumentationComments(indent, documentationComments, _docCommentSpec); @@ -1482,16 +1478,14 @@ fun deepEquals(a: Any?, b: Any?): Boolean { methodArguments.add(argName); }); } - final String call = - onCreateCall != null - ? onCreateCall(methodArguments, apiVarName: 'api') - : 'api.$name(${methodArguments.join(', ')})'; + final String call = onCreateCall != null + ? onCreateCall(methodArguments, apiVarName: 'api') + : 'api.$name(${methodArguments.join(', ')})'; if (isAsynchronous) { - final String resultType = - returnType.isVoid - ? 'Unit' - : _nullSafeKotlinTypeForDartType(returnType); + final String resultType = returnType.isVoid + ? 'Unit' + : _nullSafeKotlinTypeForDartType(returnType); indent.write(methodArguments.isNotEmpty ? '$call ' : 'api.$name'); indent.addScoped('{ result: Result<$resultType> ->', '}', () { indent.writeln('val error = result.exceptionOrNull()'); @@ -1766,19 +1760,17 @@ fun deepEquals(a: Any?, b: Any?): Boolean { for (final Constructor constructor in api.constructors) { _writeMethodDeclaration( indent, - name: - constructor.name.isNotEmpty - ? constructor.name - : '${classMemberNamePrefix}defaultConstructor', + name: constructor.name.isNotEmpty + ? constructor.name + : '${classMemberNamePrefix}defaultConstructor', returnType: apiAsTypeDeclaration, documentationComments: constructor.documentationComments, - minApiRequirement: - _findAndroidHighestApiRequirement([ - apiAsTypeDeclaration, - ...constructor.parameters.map( - (Parameter parameter) => parameter.type, - ), - ])?.version, + minApiRequirement: _findAndroidHighestApiRequirement([ + apiAsTypeDeclaration, + ...constructor.parameters.map( + (Parameter parameter) => parameter.type, + ), + ])?.version, isAbstract: true, parameters: [ ...api.unattachedFields.map((ApiField field) { @@ -1804,11 +1796,10 @@ fun deepEquals(a: Any?, b: Any?): Boolean { documentationComments: field.documentationComments, returnType: field.type, isAbstract: true, - minApiRequirement: - _findAndroidHighestApiRequirement([ - apiAsTypeDeclaration, - field.type, - ])?.version, + minApiRequirement: _findAndroidHighestApiRequirement([ + apiAsTypeDeclaration, + field.type, + ])?.version, parameters: [ if (!field.isStatic) Parameter( @@ -1834,11 +1825,10 @@ fun deepEquals(a: Any?, b: Any?): Boolean { documentationComments: field.documentationComments, returnType: field.type, isAbstract: true, - minApiRequirement: - _findAndroidHighestApiRequirement([ - apiAsTypeDeclaration, - field.type, - ])?.version, + minApiRequirement: _findAndroidHighestApiRequirement([ + apiAsTypeDeclaration, + field.type, + ])?.version, parameters: [ Parameter( name: '${classMemberNamePrefix}instance', @@ -1865,12 +1855,11 @@ fun deepEquals(a: Any?, b: Any?): Boolean { documentationComments: method.documentationComments, isAsynchronous: method.isAsynchronous, isAbstract: true, - minApiRequirement: - _findAndroidHighestApiRequirement([ - if (!method.isStatic) apiAsTypeDeclaration, - method.returnType, - ...method.parameters.map((Parameter p) => p.type), - ])?.version, + minApiRequirement: _findAndroidHighestApiRequirement([ + if (!method.isStatic) apiAsTypeDeclaration, + method.returnType, + ...method.parameters.map((Parameter p) => p.type), + ])?.version, parameters: [ if (!method.isStatic) Parameter( @@ -1948,10 +1937,9 @@ fun deepEquals(a: Any?, b: Any?): Boolean { } for (final Constructor constructor in api.constructors) { - final String name = - constructor.name.isNotEmpty - ? constructor.name - : '${classMemberNamePrefix}defaultConstructor'; + final String name = constructor.name.isNotEmpty + ? constructor.name + : '${classMemberNamePrefix}defaultConstructor'; final String channelName = makeChannelNameWithStrings( apiName: api.name, methodName: name, @@ -1972,13 +1960,14 @@ fun deepEquals(a: Any?, b: Any?): Boolean { channelName: channelName, taskQueueType: TaskQueueType.serial, returnType: const TypeDeclaration.voidDeclaration(), - onCreateCall: ( - List methodParameters, { - required String apiVarName, - }) { - return '$apiVarName.pigeonRegistrar.instanceManager.addDartCreatedInstance(' - '$apiVarName.$name(${methodParameters.skip(1).join(',')}), ${methodParameters.first})'; - }, + onCreateCall: + ( + List methodParameters, { + required String apiVarName, + }) { + return '$apiVarName.pigeonRegistrar.instanceManager.addDartCreatedInstance(' + '$apiVarName.$name(${methodParameters.skip(1).join(',')}), ${methodParameters.first})'; + }, parameters: [ Parameter( name: '${classMemberNamePrefix}identifier', @@ -2014,15 +2003,17 @@ fun deepEquals(a: Any?, b: Any?): Boolean { channelName: channelName, taskQueueType: TaskQueueType.serial, returnType: const TypeDeclaration.voidDeclaration(), - onCreateCall: ( - List methodParameters, { - required String apiVarName, - }) { - final String param = - methodParameters.length > 1 ? methodParameters.first : ''; - return '$apiVarName.pigeonRegistrar.instanceManager.addDartCreatedInstance(' - '$apiVarName.${field.name}($param), ${methodParameters.last})'; - }, + onCreateCall: + ( + List methodParameters, { + required String apiVarName, + }) { + final String param = methodParameters.length > 1 + ? methodParameters.first + : ''; + return '$apiVarName.pigeonRegistrar.instanceManager.addDartCreatedInstance(' + '$apiVarName.${field.name}($param), ${methodParameters.last})'; + }, parameters: [ if (!field.isStatic) Parameter( @@ -2107,11 +2098,10 @@ fun deepEquals(a: Any?, b: Any?): Boolean { methodName: newInstanceMethodName, dartPackageName: dartPackageName, ), - minApiRequirement: - _findAndroidHighestApiRequirement([ - apiAsTypeDeclaration, - ...api.unattachedFields.map((ApiField field) => field.type), - ])?.version, + minApiRequirement: _findAndroidHighestApiRequirement([ + apiAsTypeDeclaration, + ...api.unattachedFields.map((ApiField field) => field.type), + ])?.version, dartPackageName: dartPackageName, parameters: [ Parameter( @@ -2123,75 +2113,81 @@ fun deepEquals(a: Any?, b: Any?): Boolean { ), ), ], - onWriteBody: ( - Indent indent, { - required InternalKotlinOptions generatorOptions, - required List parameters, - required TypeDeclaration returnType, - required String channelName, - required String errorClassName, - }) { - indent.writeScoped('if (pigeonRegistrar.ignoreCallsToDart) {', '}', () { - indent.format( - ''' + onWriteBody: + ( + Indent indent, { + required InternalKotlinOptions generatorOptions, + required List parameters, + required TypeDeclaration returnType, + required String channelName, + required String errorClassName, + }) { + indent.writeScoped( + 'if (pigeonRegistrar.ignoreCallsToDart) {', + '}', + () { + indent.format( + ''' callback( Result.failure( $errorClassName("ignore-calls-error", "Calls to Dart are being ignored.", "")))''', - ); - }, addTrailingNewline: false); - indent.writeScoped( - ' else if (pigeonRegistrar.instanceManager.containsInstance(${classMemberNamePrefix}instanceArg)) {', - '}', - () { - indent.writeln('callback(Result.success(Unit))'); - }, - addTrailingNewline: false, - ); - indent.writeScoped(' else {', '}', () { - if (api.hasCallbackConstructor()) { - indent.writeln( - 'val ${classMemberNamePrefix}identifierArg = pigeonRegistrar.instanceManager.addHostCreatedInstance(${classMemberNamePrefix}instanceArg)', - ); - enumerate(api.unattachedFields, (int index, ApiField field) { - final String argName = _getSafeArgumentName(index, field); - indent.writeln( - 'val $argName = ${field.name}(${classMemberNamePrefix}instanceArg)', - ); - }); - - indent.writeln( - 'val binaryMessenger = pigeonRegistrar.binaryMessenger', + ); + }, + addTrailingNewline: false, ); - indent.writeln('val codec = pigeonRegistrar.codec'); - _writeFlutterMethodMessageCall( - indent, - generatorOptions: generatorOptions, - returnType: returnType, - channelName: channelName, - errorClassName: errorClassName, - parameters: [ - Parameter( - name: '${classMemberNamePrefix}identifier', - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), - ), - ...api.unattachedFields.map((ApiField field) { - return Parameter(name: field.name, type: field.type); - }), - ], + indent.writeScoped( + ' else if (pigeonRegistrar.instanceManager.containsInstance(${classMemberNamePrefix}instanceArg)) {', + '}', + () { + indent.writeln('callback(Result.success(Unit))'); + }, + addTrailingNewline: false, ); - } else { - indent.format( - ''' + indent.writeScoped(' else {', '}', () { + if (api.hasCallbackConstructor()) { + indent.writeln( + 'val ${classMemberNamePrefix}identifierArg = pigeonRegistrar.instanceManager.addHostCreatedInstance(${classMemberNamePrefix}instanceArg)', + ); + enumerate(api.unattachedFields, (int index, ApiField field) { + final String argName = _getSafeArgumentName(index, field); + indent.writeln( + 'val $argName = ${field.name}(${classMemberNamePrefix}instanceArg)', + ); + }); + + indent.writeln( + 'val binaryMessenger = pigeonRegistrar.binaryMessenger', + ); + indent.writeln('val codec = pigeonRegistrar.codec'); + _writeFlutterMethodMessageCall( + indent, + generatorOptions: generatorOptions, + returnType: returnType, + channelName: channelName, + errorClassName: errorClassName, + parameters: [ + Parameter( + name: '${classMemberNamePrefix}identifier', + type: const TypeDeclaration( + baseName: 'int', + isNullable: false, + ), + ), + ...api.unattachedFields.map((ApiField field) { + return Parameter(name: field.name, type: field.type); + }), + ], + ); + } else { + indent.format( + ''' callback( Result.failure( $errorClassName("new-instance-error", "Attempting to create a new Dart instance of ${api.name}, but the class has a nonnull callback method.", "")))''', - ); - } - }); - }, + ); + } + }); + }, ); indent.newln(); } @@ -2213,12 +2209,11 @@ fun deepEquals(a: Any?, b: Any?): Boolean { channelName: makeChannelName(api, method, dartPackageName), dartPackageName: dartPackageName, documentationComments: method.documentationComments, - minApiRequirement: - _findAndroidHighestApiRequirement([ - apiAsTypeDeclaration, - method.returnType, - ...method.parameters.map((Parameter parameter) => parameter.type), - ])?.version, + minApiRequirement: _findAndroidHighestApiRequirement([ + apiAsTypeDeclaration, + method.returnType, + ...method.parameters.map((Parameter parameter) => parameter.type), + ])?.version, parameters: [ Parameter( name: '${classMemberNamePrefix}instance', @@ -2230,38 +2225,39 @@ fun deepEquals(a: Any?, b: Any?): Boolean { ), ...method.parameters, ], - onWriteBody: ( - Indent indent, { - required InternalKotlinOptions generatorOptions, - required List parameters, - required TypeDeclaration returnType, - required String channelName, - required String errorClassName, - }) { - indent.writeScoped( - 'if (pigeonRegistrar.ignoreCallsToDart) {', - '}', - () { - indent.format(''' + onWriteBody: + ( + Indent indent, { + required InternalKotlinOptions generatorOptions, + required List parameters, + required TypeDeclaration returnType, + required String channelName, + required String errorClassName, + }) { + indent.writeScoped( + 'if (pigeonRegistrar.ignoreCallsToDart) {', + '}', + () { + indent.format(''' callback( Result.failure( $errorClassName("ignore-calls-error", "Calls to Dart are being ignored.", ""))) return'''); + }, + ); + indent.writeln( + 'val binaryMessenger = pigeonRegistrar.binaryMessenger', + ); + indent.writeln('val codec = pigeonRegistrar.codec'); + _writeFlutterMethodMessageCall( + indent, + generatorOptions: generatorOptions, + returnType: returnType, + channelName: channelName, + errorClassName: errorClassName, + parameters: parameters, + ); }, - ); - indent.writeln( - 'val binaryMessenger = pigeonRegistrar.binaryMessenger', - ); - indent.writeln('val codec = pigeonRegistrar.codec'); - _writeFlutterMethodMessageCall( - indent, - generatorOptions: generatorOptions, - returnType: returnType, - channelName: channelName, - errorClassName: errorClassName, - parameters: parameters, - ); - }, ); indent.newln(); } diff --git a/packages/pigeon/lib/src/objc/objc_generator.dart b/packages/pigeon/lib/src/objc/objc_generator.dart index 8af4ed31742..57ca9840e3f 100644 --- a/packages/pigeon/lib/src/objc/objc_generator.dart +++ b/packages/pigeon/lib/src/objc/objc_generator.dart @@ -810,8 +810,10 @@ if (self.wrapped == nil) { required String dartPackageName, }) { const String codecName = 'PigeonCodec'; - final List enumeratedTypes = - getEnumeratedTypes(root, excludeSealedClasses: true).toList(); + final List enumeratedTypes = getEnumeratedTypes( + root, + excludeSealedClasses: true, + ).toList(); final String readerWriterName = '${generatorOptions.prefix}${toUpperCamelCase(generatorOptions.fileSpecificClassNameComponent ?? '')}${codecName}ReaderWriter'; final String readerName = @@ -868,22 +870,19 @@ if (self.wrapped == nil) { indent.addScoped('{', '}', () { indent.write(''); for (final EnumeratedType customType in enumeratedTypes) { - final String encodeString = - customType.type == CustomTypes.customClass - ? '[value toList]' - : '(value == nil ? [NSNull null] : [NSNumber numberWithInteger:box.value])'; - final String valueString = - customType.enumeration < maximumCodecFieldKey - ? encodeString - : '[wrap toList]'; - final String className = - customType.type == CustomTypes.customClass - ? _className(generatorOptions.prefix, customType.name) - : _enumName( - customType.name, - prefix: generatorOptions.prefix, - box: true, - ); + final String encodeString = customType.type == CustomTypes.customClass + ? '[value toList]' + : '(value == nil ? [NSNull null] : [NSNumber numberWithInteger:box.value])'; + final String valueString = customType.enumeration < maximumCodecFieldKey + ? encodeString + : '[wrap toList]'; + final String className = customType.type == CustomTypes.customClass + ? _className(generatorOptions.prefix, customType.name) + : _enumName( + customType.name, + prefix: generatorOptions.prefix, + box: true, + ); indent.addScoped( 'if ([value isKindOfClass:[$className class]]) {', '} else ', @@ -893,8 +892,8 @@ if (self.wrapped == nil) { } final int enumeration = customType.enumeration < maximumCodecFieldKey - ? customType.enumeration - : maximumCodecFieldKey; + ? customType.enumeration + : maximumCodecFieldKey; if (customType.enumeration >= maximumCodecFieldKey) { indent.writeln( '${_className(generatorOptions.prefix, _overflowClassName)} *wrap = [${_className(generatorOptions.prefix, _overflowClassName)} makeWithType:${customType.enumeration - maximumCodecFieldKey} wrapped:$encodeString];', @@ -1234,8 +1233,9 @@ static FlutterError *createConnectionError(NSString *channelName) { } // TODO(gaaclarke): Incorporate this into _getSelectorComponents. - final String lastSelectorComponent = - func.isAsynchronous ? 'completion' : 'error'; + final String lastSelectorComponent = func.isAsynchronous + ? 'completion' + : 'error'; final String selector = _getSelector(func, lastSelectorComponent); indent.writeln( 'NSCAssert([api respondsToSelector:@selector($selector)], @"$apiName api (%@) doesn\'t respond to @selector($selector)", api);', @@ -1271,10 +1271,9 @@ static FlutterError *createConnectionError(NSString *channelName) { if (func.isAsynchronous) { writeAsyncBindings(selectorComponents, callSignature, returnType); } else { - final String syncCall = - func.parameters.isEmpty - ? '[api ${selectorComponents.first}:&error]' - : '[api $callSignature error:&error]'; + final String syncCall = func.parameters.isEmpty + ? '[api ${selectorComponents.first}:&error]' + : '[api $callSignature error:&error]'; writeSyncBindings(syncCall, returnType); } }); @@ -1504,25 +1503,22 @@ void _writeObjcSourceClassInitializerDeclaration( classDefinition, )) { final String label = isFirst ? _capitalize(field.name) : field.name; - final void Function(String) printer = - isFirst - ? indent.add - : (String x) { - indent.newln(); - indent.write(x); - }; + final void Function(String) printer = isFirst + ? indent.add + : (String x) { + indent.newln(); + indent.write(x); + }; isFirst = false; final HostDatatype hostDatatype = getFieldHostDatatype( field, (TypeDeclaration x) => _objcTypeStringForPrimitiveDartType(prefix, x, beforeString: true), - customResolver: - field.type.isEnum - ? (String x) => - field.type.isNullable - ? _enumName(x, suffix: ' *', prefix: prefix, box: true) - : _enumName(x, prefix: prefix) - : (String x) => '${_className(prefix, x)} *', + customResolver: field.type.isEnum + ? (String x) => field.type.isNullable + ? _enumName(x, suffix: ' *', prefix: prefix, box: true) + : _enumName(x, prefix: prefix) + : (String x) => '${_className(prefix, x)} *', ); final String nullable = field.type.isNullable ? 'nullable ' : ''; printer('$label:($nullable${hostDatatype.datatype})${field.name}'); @@ -1692,15 +1688,13 @@ String? _objcTypeStringForPrimitiveDartType( }) { final _ObjcType? objcType; if (forceBox || type.isNullable) { - objcType = - _objcTypeForNullableDartTypeMap.containsKey(type.baseName) - ? _objcTypeForDartType(classPrefix, type) - : null; + objcType = _objcTypeForNullableDartTypeMap.containsKey(type.baseName) + ? _objcTypeForDartType(classPrefix, type) + : null; } else { - objcType = - _objcTypeForNonNullableDartTypeMap.containsKey(type.baseName) - ? _objcTypeForDartType(classPrefix, type) - : null; + objcType = _objcTypeForNonNullableDartTypeMap.containsKey(type.baseName) + ? _objcTypeForDartType(classPrefix, type) + : null; } return beforeString ? objcType?.beforeString : objcType?.toString(); } @@ -1718,16 +1712,16 @@ _ObjcType _objcTypeForDartType( ); return primitiveType == null ? _ObjcType( - baseName: _className(classPrefix, field.baseName), - // Non-nullable enums are non-pointer types. - isPointer: !field.isEnum || (field.isNullable || forceBox), - ) + baseName: _className(classPrefix, field.baseName), + // Non-nullable enums are non-pointer types. + isPointer: !field.isEnum || (field.isNullable || forceBox), + ) : field.typeArguments.isEmpty ? primitiveType : _ObjcType( - baseName: - '${primitiveType.baseName}<${_flattenTypeArguments(classPrefix, field.typeArguments)}>', - ); + baseName: + '${primitiveType.baseName}<${_flattenTypeArguments(classPrefix, field.typeArguments)}>', + ); } /// Maps a type to a properties memory semantics (ie strong, copy). @@ -1775,8 +1769,8 @@ Iterable _getSelectorComponents( final bool hasArguments = it.moveNext(); final String namePostfix = (lastSelectorComponent.isNotEmpty && func.parameters.isEmpty) - ? 'With${_capitalize(lastSelectorComponent)}' - : ''; + ? 'With${_capitalize(lastSelectorComponent)}' + : ''; yield '${func.name}${hasArguments ? _capitalize(func.parameters[0].name) : namePostfix}'; while (it.moveNext()) { yield it.current.name; @@ -1991,10 +1985,9 @@ void _writeDataClassDeclaration( field, (TypeDeclaration x) => _objcTypeStringForPrimitiveDartType(prefix, x, beforeString: true), - customResolver: - field.type.isEnum - ? (String x) => _enumName(x, prefix: prefix) - : (String x) => '${_className(prefix, x)} *', + customResolver: field.type.isEnum + ? (String x) => _enumName(x, prefix: prefix) + : (String x) => '${_className(prefix, x)} *', ); late final String propertyType; addDocumentationComments( @@ -2008,15 +2001,14 @@ void _writeDataClassDeclaration( isEnum: field.type.isEnum, ); final String nullability = field.type.isNullable ? ', nullable' : ''; - final String fieldType = - field.type.isEnum && field.type.isNullable - ? _enumName( - field.type.baseName, - suffix: ' *', - prefix: generatorOptions.prefix, - box: field.type.isNullable, - ) - : hostDatatype.datatype; + final String fieldType = field.type.isEnum && field.type.isNullable + ? _enumName( + field.type.baseName, + suffix: ' *', + prefix: generatorOptions.prefix, + box: field.type.isNullable, + ) + : hostDatatype.datatype; indent.writeln( '@property(nonatomic, $propertyType$nullability) $fieldType ${field.name};', ); diff --git a/packages/pigeon/lib/src/pigeon_lib.dart b/packages/pigeon/lib/src/pigeon_lib.dart index 9e00f0f2ee5..676c0e42815 100644 --- a/packages/pigeon/lib/src/pigeon_lib.dart +++ b/packages/pigeon/lib/src/pigeon_lib.dart @@ -348,47 +348,36 @@ class PigeonOptions { dartTestOut: map['dartTestOut'] as String?, objcHeaderOut: map['objcHeaderOut'] as String?, objcSourceOut: map['objcSourceOut'] as String?, - objcOptions: - map.containsKey('objcOptions') - ? ObjcOptions.fromMap(map['objcOptions']! as Map) - : null, + objcOptions: map.containsKey('objcOptions') + ? ObjcOptions.fromMap(map['objcOptions']! as Map) + : null, javaOut: map['javaOut'] as String?, - javaOptions: - map.containsKey('javaOptions') - ? JavaOptions.fromMap(map['javaOptions']! as Map) - : null, + javaOptions: map.containsKey('javaOptions') + ? JavaOptions.fromMap(map['javaOptions']! as Map) + : null, swiftOut: map['swiftOut'] as String?, - swiftOptions: - map.containsKey('swiftOptions') - ? SwiftOptions.fromList( - map['swiftOptions']! as Map, - ) - : null, + swiftOptions: map.containsKey('swiftOptions') + ? SwiftOptions.fromList(map['swiftOptions']! as Map) + : null, kotlinOut: map['kotlinOut'] as String?, - kotlinOptions: - map.containsKey('kotlinOptions') - ? KotlinOptions.fromMap( - map['kotlinOptions']! as Map, - ) - : null, + kotlinOptions: map.containsKey('kotlinOptions') + ? KotlinOptions.fromMap(map['kotlinOptions']! as Map) + : null, cppHeaderOut: map['cppHeaderOut'] as String?, cppSourceOut: map['cppSourceOut'] as String?, - cppOptions: - map.containsKey('cppOptions') - ? CppOptions.fromMap(map['cppOptions']! as Map) - : null, + cppOptions: map.containsKey('cppOptions') + ? CppOptions.fromMap(map['cppOptions']! as Map) + : null, gobjectHeaderOut: map['gobjectHeaderOut'] as String?, gobjectSourceOut: map['gobjectSourceOut'] as String?, - gobjectOptions: - map.containsKey('gobjectOptions') - ? GObjectOptions.fromMap( - map['gobjectOptions']! as Map, - ) - : null, - dartOptions: - map.containsKey('dartOptions') - ? DartOptions.fromMap(map['dartOptions']! as Map) - : null, + gobjectOptions: map.containsKey('gobjectOptions') + ? GObjectOptions.fromMap( + map['gobjectOptions']! as Map, + ) + : null, + dartOptions: map.containsKey('dartOptions') + ? DartOptions.fromMap(map['dartOptions']! as Map) + : null, copyrightHeader: map['copyrightHeader'] as String?, astOut: map['astOut'] as String?, debugGenerators: map['debugGenerators'] as bool?, @@ -521,115 +510,113 @@ options: ${_argParser.usage}'''; } - static final ArgParser _argParser = - ArgParser() - ..addOption('input', help: 'REQUIRED: Path to pigeon file.') - ..addOption( - 'dart_out', - help: - 'Path to generated Dart source file (.dart). ' - 'Required if one_language is not specified.', - ) - ..addOption( - 'dart_test_out', - help: - 'Path to generated library for Dart tests, when using ' - '@HostApi(dartHostTestHandler:).', - ) - ..addOption( - 'objc_source_out', - help: 'Path to generated Objective-C source file (.m).', - ) - ..addOption('java_out', help: 'Path to generated Java file (.java).') - ..addOption( - 'java_package', - help: 'The package that generated Java code will be in.', - ) - ..addFlag( - 'java_use_generated_annotation', - help: 'Adds the java.annotation.Generated annotation to the output.', - ) - ..addOption( - 'swift_out', - help: 'Path to generated Swift file (.swift).', - aliases: const ['experimental_swift_out'], - ) - ..addOption( - 'kotlin_out', - help: 'Path to generated Kotlin file (.kt).', - aliases: const ['experimental_kotlin_out'], - ) - ..addOption( - 'kotlin_package', - help: 'The package that generated Kotlin code will be in.', - aliases: const ['experimental_kotlin_package'], - ) - ..addOption( - 'cpp_header_out', - help: 'Path to generated C++ header file (.h).', - aliases: const ['experimental_cpp_header_out'], - ) - ..addOption( - 'cpp_source_out', - help: 'Path to generated C++ classes file (.cpp).', - aliases: const ['experimental_cpp_source_out'], - ) - ..addOption( - 'cpp_namespace', - help: 'The namespace that generated C++ code will be in.', - ) - ..addOption( - 'gobject_header_out', - help: 'Path to generated GObject header file (.h).', - aliases: const ['experimental_gobject_header_out'], - ) - ..addOption( - 'gobject_source_out', - help: 'Path to generated GObject classes file (.cc).', - aliases: const ['experimental_gobject_source_out'], - ) - ..addOption( - 'gobject_module', - help: 'The module that generated GObject code will be in.', - ) - ..addOption( - 'objc_header_out', - help: 'Path to generated Objective-C header file (.h).', - ) - ..addOption( - 'objc_prefix', - help: 'Prefix for generated Objective-C classes and protocols.', - ) - ..addOption( - 'copyright_header', - help: - 'Path to file with copyright header to be prepended to generated code.', - ) - ..addFlag( - 'one_language', - hide: true, - help: 'Does nothing, only here to avoid breaking changes', - ) - ..addOption( - 'ast_out', - help: - 'Path to generated AST debugging info. (Warning: format subject to change)', - ) - ..addFlag( - 'debug_generators', - help: - 'Print the line number of the generator in comments at newlines.', - ) - ..addOption( - 'base_path', - help: - 'A base path to be prefixed to all outputs and copyright header path. Generally used for testing', - hide: true, - ) - ..addOption( - 'package_name', - help: 'The package that generated code will be in.', - ); + static final ArgParser _argParser = ArgParser() + ..addOption('input', help: 'REQUIRED: Path to pigeon file.') + ..addOption( + 'dart_out', + help: + 'Path to generated Dart source file (.dart). ' + 'Required if one_language is not specified.', + ) + ..addOption( + 'dart_test_out', + help: + 'Path to generated library for Dart tests, when using ' + '@HostApi(dartHostTestHandler:).', + ) + ..addOption( + 'objc_source_out', + help: 'Path to generated Objective-C source file (.m).', + ) + ..addOption('java_out', help: 'Path to generated Java file (.java).') + ..addOption( + 'java_package', + help: 'The package that generated Java code will be in.', + ) + ..addFlag( + 'java_use_generated_annotation', + help: 'Adds the java.annotation.Generated annotation to the output.', + ) + ..addOption( + 'swift_out', + help: 'Path to generated Swift file (.swift).', + aliases: const ['experimental_swift_out'], + ) + ..addOption( + 'kotlin_out', + help: 'Path to generated Kotlin file (.kt).', + aliases: const ['experimental_kotlin_out'], + ) + ..addOption( + 'kotlin_package', + help: 'The package that generated Kotlin code will be in.', + aliases: const ['experimental_kotlin_package'], + ) + ..addOption( + 'cpp_header_out', + help: 'Path to generated C++ header file (.h).', + aliases: const ['experimental_cpp_header_out'], + ) + ..addOption( + 'cpp_source_out', + help: 'Path to generated C++ classes file (.cpp).', + aliases: const ['experimental_cpp_source_out'], + ) + ..addOption( + 'cpp_namespace', + help: 'The namespace that generated C++ code will be in.', + ) + ..addOption( + 'gobject_header_out', + help: 'Path to generated GObject header file (.h).', + aliases: const ['experimental_gobject_header_out'], + ) + ..addOption( + 'gobject_source_out', + help: 'Path to generated GObject classes file (.cc).', + aliases: const ['experimental_gobject_source_out'], + ) + ..addOption( + 'gobject_module', + help: 'The module that generated GObject code will be in.', + ) + ..addOption( + 'objc_header_out', + help: 'Path to generated Objective-C header file (.h).', + ) + ..addOption( + 'objc_prefix', + help: 'Prefix for generated Objective-C classes and protocols.', + ) + ..addOption( + 'copyright_header', + help: + 'Path to file with copyright header to be prepended to generated code.', + ) + ..addFlag( + 'one_language', + hide: true, + help: 'Does nothing, only here to avoid breaking changes', + ) + ..addOption( + 'ast_out', + help: + 'Path to generated AST debugging info. (Warning: format subject to change)', + ) + ..addFlag( + 'debug_generators', + help: 'Print the line number of the generator in comments at newlines.', + ) + ..addOption( + 'base_path', + help: + 'A base path to be prefixed to all outputs and copyright header path. Generally used for testing', + hide: true, + ) + ..addOption( + 'package_name', + help: 'The package that generated code will be in.', + ); /// Convert command-line arguments to [PigeonOptions]. static PigeonOptions parseArgs(List args) { diff --git a/packages/pigeon/lib/src/pigeon_lib_internal.dart b/packages/pigeon/lib/src/pigeon_lib_internal.dart index 19c3be1fef9..3c5c67946e3 100644 --- a/packages/pigeon/lib/src/pigeon_lib_internal.dart +++ b/packages/pigeon/lib/src/pigeon_lib_internal.dart @@ -53,81 +53,74 @@ class InternalPigeonOptions { ) : input = options.input, objcOptions = (options.objcHeaderOut == null || options.objcSourceOut == null) - ? null - : InternalObjcOptions.fromObjcOptions( - options.objcOptions ?? const ObjcOptions(), - objcHeaderOut: options.objcHeaderOut!, - objcSourceOut: options.objcSourceOut!, - fileSpecificClassNameComponent: - options.objcSourceOut - ?.split('/') - .lastOrNull - ?.split('.') - .firstOrNull ?? - '', - copyrightHeader: copyrightHeader, - ), - javaOptions = - options.javaOut == null - ? null - : InternalJavaOptions.fromJavaOptions( - options.javaOptions ?? const JavaOptions(), - javaOut: options.javaOut!, - copyrightHeader: copyrightHeader, - ), - swiftOptions = - options.swiftOut == null - ? null - : InternalSwiftOptions.fromSwiftOptions( - options.swiftOptions ?? const SwiftOptions(), - swiftOut: options.swiftOut!, - copyrightHeader: copyrightHeader, - ), - kotlinOptions = - options.kotlinOut == null - ? null - : InternalKotlinOptions.fromKotlinOptions( - options.kotlinOptions ?? const KotlinOptions(), - kotlinOut: options.kotlinOut!, - copyrightHeader: copyrightHeader, - ), + ? null + : InternalObjcOptions.fromObjcOptions( + options.objcOptions ?? const ObjcOptions(), + objcHeaderOut: options.objcHeaderOut!, + objcSourceOut: options.objcSourceOut!, + fileSpecificClassNameComponent: + options.objcSourceOut + ?.split('/') + .lastOrNull + ?.split('.') + .firstOrNull ?? + '', + copyrightHeader: copyrightHeader, + ), + javaOptions = options.javaOut == null + ? null + : InternalJavaOptions.fromJavaOptions( + options.javaOptions ?? const JavaOptions(), + javaOut: options.javaOut!, + copyrightHeader: copyrightHeader, + ), + swiftOptions = options.swiftOut == null + ? null + : InternalSwiftOptions.fromSwiftOptions( + options.swiftOptions ?? const SwiftOptions(), + swiftOut: options.swiftOut!, + copyrightHeader: copyrightHeader, + ), + kotlinOptions = options.kotlinOut == null + ? null + : InternalKotlinOptions.fromKotlinOptions( + options.kotlinOptions ?? const KotlinOptions(), + kotlinOut: options.kotlinOut!, + copyrightHeader: copyrightHeader, + ), cppOptions = (options.cppHeaderOut == null || options.cppSourceOut == null) - ? null - : InternalCppOptions.fromCppOptions( - options.cppOptions ?? const CppOptions(), - cppHeaderOut: options.cppHeaderOut!, - cppSourceOut: options.cppSourceOut!, - copyrightHeader: copyrightHeader, - ), + ? null + : InternalCppOptions.fromCppOptions( + options.cppOptions ?? const CppOptions(), + cppHeaderOut: options.cppHeaderOut!, + cppSourceOut: options.cppSourceOut!, + copyrightHeader: copyrightHeader, + ), gobjectOptions = options.gobjectHeaderOut == null || options.gobjectSourceOut == null - ? null - : InternalGObjectOptions.fromGObjectOptions( - options.gobjectOptions ?? const GObjectOptions(), - gobjectHeaderOut: options.gobjectHeaderOut!, - gobjectSourceOut: options.gobjectSourceOut!, - copyrightHeader: copyrightHeader, - ), + ? null + : InternalGObjectOptions.fromGObjectOptions( + options.gobjectOptions ?? const GObjectOptions(), + gobjectHeaderOut: options.gobjectHeaderOut!, + gobjectSourceOut: options.gobjectSourceOut!, + copyrightHeader: copyrightHeader, + ), dartOptions = (options.dartOut == null && - options.dartOptions?.sourceOutPath == null) - ? null - : InternalDartOptions.fromDartOptions( - options.dartOptions ?? const DartOptions(), - dartOut: options.dartOut, - testOut: options.dartTestOut, - copyrightHeader: copyrightHeader, - ), - copyrightHeader = - options.copyrightHeader != null - ? _lineReader( - path.posix.join( - options.basePath ?? '', - options.copyrightHeader, - ), - ) - : null, + options.dartOptions?.sourceOutPath == null) + ? null + : InternalDartOptions.fromDartOptions( + options.dartOptions ?? const DartOptions(), + dartOut: options.dartOut, + testOut: options.dartTestOut, + copyrightHeader: copyrightHeader, + ), + copyrightHeader = options.copyrightHeader != null + ? _lineReader( + path.posix.join(options.basePath ?? '', options.copyrightHeader), + ) + : null, astOut = options.astOut, debugGenerators = options.debugGenerators, basePath = options.basePath, @@ -135,12 +128,11 @@ class InternalPigeonOptions { /// Creates a instance of InternalPigeonOptions from PigeonOptions. static InternalPigeonOptions fromPigeonOptions(PigeonOptions options) { - final Iterable? copyrightHeader = - options.copyrightHeader != null - ? _lineReader( - path.posix.join(options.basePath ?? '', options.copyrightHeader), - ) - : null; + final Iterable? copyrightHeader = options.copyrightHeader != null + ? _lineReader( + path.posix.join(options.basePath ?? '', options.copyrightHeader), + ) + : null; return InternalPigeonOptions._fromPigeonOptionsWithHeader( options, @@ -719,8 +711,9 @@ extension _ObjectAs on Object { List _validateAst(Root root, String source) { final List result = []; - final List customClasses = - root.classes.map((Class x) => x.name).toList(); + final List customClasses = root.classes + .map((Class x) => x.name) + .toList(); final Iterable customEnums = root.enums.map((Enum x) => x.name); for (final Enum enumDefinition in root.enums) { final String? matchingPrefix = _findMatchingPrefixOrNull( @@ -1308,8 +1301,9 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { _apis, _classes, ); - final Set referencedTypeNames = - referencedTypes.keys.map((TypeDeclaration e) => e.baseName).toSet(); + final Set referencedTypeNames = referencedTypes.keys + .map((TypeDeclaration e) => e.baseName) + .toSet(); final List nonReferencedTypes = List.from(_classes); nonReferencedTypes.removeWhere( (Class x) => referencedTypeNames.contains(x.name), @@ -1364,10 +1358,9 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { element.key.baseName != 'dynamic' && element.key.baseName != 'Object' && element.key.baseName.isNotEmpty) { - final int? lineNumber = - element.value.isEmpty - ? null - : calculateLineNumber(source, element.value.first); + final int? lineNumber = element.value.isEmpty + ? null + : calculateLineNumber(source, element.value.first); totalErrors.add( Error( message: 'Unknown type: ${element.key.baseName}', @@ -1412,10 +1405,9 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { totalErrors.addAll(validateErrors); return ParseResults( - root: - totalErrors.isEmpty - ? completeRoot - : Root(apis: [], classes: [], enums: []), + root: totalErrors.isEmpty + ? completeRoot + : Root(apis: [], classes: [], enums: []), errors: totalErrors, pigeonOptions: _pigeonOptions, ); @@ -1804,10 +1796,9 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { const String docCommentPrefix = '///'; return comments ?.map( - (Token line) => - line.length > docCommentPrefix.length - ? line.toString().substring(docCommentPrefix.length) - : '', + (Token line) => line.length > docCommentPrefix.length + ? line.toString().substring(docCommentPrefix.length) + : '', ) .toList() ?? []; @@ -1892,8 +1883,9 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { @override Object? visitMethodDeclaration(dart_ast.MethodDeclaration node) { final dart_ast.FormalParameterList parameters = node.parameters!; - final List arguments = - parameters.parameters.map(_formalParameterToPigeonParameter).toList(); + final List arguments = parameters.parameters + .map(_formalParameterToPigeonParameter) + .toList(); final bool isAsynchronous = _hasMetadata(node.metadata, 'async'); final bool isStatic = _hasMetadata(node.metadata, 'static'); final String objcSelector = @@ -1909,14 +1901,15 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { .asNullable() ?.value ?? ''; - final dart_ast.ArgumentList? taskQueueArguments = - _findMetadata(node.metadata, 'TaskQueue')?.arguments; - final String? taskQueueTypeName = - taskQueueArguments == null - ? null - : _getFirstChildOfType( - taskQueueArguments, - )?.expression.asNullable()?.name; + final dart_ast.ArgumentList? taskQueueArguments = _findMetadata( + node.metadata, + 'TaskQueue', + )?.arguments; + final String? taskQueueTypeName = taskQueueArguments == null + ? null + : _getFirstChildOfType( + taskQueueArguments, + )?.expression.asNullable()?.name; final TaskQueueType taskQueueType = _stringToEnum(TaskQueueType.values, taskQueueTypeName) ?? TaskQueueType.serial; @@ -1971,17 +1964,16 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { _enums.add( Enum( name: node.name.lexeme, - members: - node.constants - .map( - (dart_ast.EnumConstantDeclaration e) => EnumMember( - name: e.name.lexeme, - documentationComments: _documentationCommentsParser( - e.documentationComment?.tokens, - ), - ), - ) - .toList(), + members: node.constants + .map( + (dart_ast.EnumConstantDeclaration e) => EnumMember( + name: e.name.lexeme, + documentationComments: _documentationCommentsParser( + e.documentationComment?.tokens, + ), + ), + ) + .toList(), documentationComments: _documentationCommentsParser( node.documentationComment?.tokens, ), @@ -2078,8 +2070,9 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { Object? visitConstructorDeclaration(dart_ast.ConstructorDeclaration node) { if (_currentApi is AstProxyApi) { final dart_ast.FormalParameterList parameters = node.parameters; - final List arguments = - parameters.parameters.map(_formalParameterToPigeonParameter).toList(); + final List arguments = parameters.parameters + .map(_formalParameterToPigeonParameter) + .toList(); final String swiftFunction = _findMetadata(node.metadata, 'SwiftFunction') ?.arguments @@ -2129,8 +2122,9 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { in node.parameters.parameters) { if (param is dart_ast.DefaultFormalParameter) { if (param.name != null && param.defaultValue != null) { - _currentClassDefaultValues[param.name!.toString()] = - param.defaultValue!.toString(); + _currentClassDefaultValues[param.name!.toString()] = param + .defaultValue! + .toString(); } } } @@ -2154,10 +2148,9 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { ) { final bool isStatic = _hasMetadata(node.metadata, 'static'); if (type is dart_ast.GenericFunctionType) { - final List parameters = - type.parameters.parameters - .map(_formalParameterToPigeonParameter) - .toList(); + final List parameters = type.parameters.parameters + .map(_formalParameterToPigeonParameter) + .toList(); final String swiftFunction = _findMetadata(node.metadata, 'SwiftFunction') ?.arguments @@ -2166,14 +2159,15 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { .asNullable() ?.value ?? ''; - final dart_ast.ArgumentList? taskQueueArguments = - _findMetadata(node.metadata, 'TaskQueue')?.arguments; - final String? taskQueueTypeName = - taskQueueArguments == null - ? null - : _getFirstChildOfType( - taskQueueArguments, - )?.expression.asNullable()?.name; + final dart_ast.ArgumentList? taskQueueArguments = _findMetadata( + node.metadata, + 'TaskQueue', + )?.arguments; + final String? taskQueueTypeName = taskQueueArguments == null + ? null + : _getFirstChildOfType( + taskQueueArguments, + )?.expression.asNullable()?.name; final TaskQueueType taskQueueType = _stringToEnum(TaskQueueType.values, taskQueueTypeName) ?? TaskQueueType.serial; diff --git a/packages/pigeon/lib/src/swift/swift_generator.dart b/packages/pigeon/lib/src/swift/swift_generator.dart index 200a7951c5b..2f30a35fd4e 100644 --- a/packages/pigeon/lib/src/swift/swift_generator.dart +++ b/packages/pigeon/lib/src/swift/swift_generator.dart @@ -263,8 +263,10 @@ class SwiftGenerator extends StructuredGenerator { final String readerName = '${codecName}Reader'; final String writerName = '${codecName}Writer'; - final List enumeratedTypes = - getEnumeratedTypes(root, excludeSealedClasses: true).toList(); + final List enumeratedTypes = getEnumeratedTypes( + root, + excludeSealedClasses: true, + ).toList(); void writeDecodeLogic(EnumeratedType customType) { indent.writeln('case ${customType.enumeration}:'); @@ -347,16 +349,16 @@ class SwiftGenerator extends StructuredGenerator { indent.addScoped('{', '} else ', () { final String encodeString = customType.type == CustomTypes.customClass - ? 'toList()' - : 'rawValue'; + ? 'toList()' + : 'rawValue'; final String valueString = customType.enumeration < maximumCodecFieldKey - ? 'value.$encodeString' - : 'wrap.toList()'; + ? 'value.$encodeString' + : 'wrap.toList()'; final int enumeration = customType.enumeration < maximumCodecFieldKey - ? customType.enumeration - : maximumCodecFieldKey; + ? customType.enumeration + : maximumCodecFieldKey; if (customType.enumeration >= maximumCodecFieldKey) { indent.writeln( 'let wrap = $_overflowClassName(type: ${customType.enumeration - maximumCodecFieldKey}, wrapped: value.$encodeString)', @@ -420,12 +422,11 @@ class SwiftGenerator extends StructuredGenerator { bool hashable = true, }) { final String privateString = private ? 'private ' : ''; - final String extendsString = - classDefinition.superClass != null - ? ': ${classDefinition.superClass!.name}' - : hashable - ? ': Hashable' - : ''; + final String extendsString = classDefinition.superClass != null + ? ': ${classDefinition.superClass!.name}' + : hashable + ? ': Hashable' + : ''; if (classDefinition.isSwiftClass) { indent.write( '${privateString}class ${classDefinition.name}$extendsString ', @@ -721,18 +722,18 @@ if (wrapped == nil) { )) { final String comma = getFieldsInSerializationOrder(classDefinition).last == field - ? '' - : ','; + ? '' + : ','; // Force-casting nullable enums in maps doesn't work the same as other types. // It needs soft-casting followed by force unwrapping. final String forceUnwrapMapWithNullableEnums = (field.type.baseName == 'Map' && - !field.type.isNullable && - field.type.typeArguments.any( - (TypeDeclaration type) => type.isEnum, - )) - ? '!' - : ''; + !field.type.isNullable && + field.type.typeArguments.any( + (TypeDeclaration type) => type.isEnum, + )) + ? '!' + : ''; indent.writeln( '${field.name}: ${field.name}$forceUnwrapMapWithNullableEnums$comma', ); @@ -942,8 +943,8 @@ if (wrapped == nil) { documentationComments: method.documentationComments, serialBackgroundQueue: method.taskQueueType == TaskQueueType.serialBackgroundThread - ? serialBackgroundQueue - : null, + ? serialBackgroundQueue + : null, ); } }); @@ -1025,12 +1026,10 @@ if (wrapped == nil) { swiftFunction: 'method(withIdentifier:)', setHandlerCondition: setHandlerCondition, isAsynchronous: false, - onCreateCall: ( - List safeArgNames, { - required String apiVarName, - }) { - return 'let _: AnyObject? = try instanceManager.removeInstance(${safeArgNames.single})'; - }, + onCreateCall: + (List safeArgNames, {required String apiVarName}) { + return 'let _: AnyObject? = try instanceManager.removeInstance(${safeArgNames.single})'; + }, ); _writeHostMethodMessageHandler( indent, @@ -1041,12 +1040,10 @@ if (wrapped == nil) { setHandlerCondition: setHandlerCondition, swiftFunction: null, isAsynchronous: false, - onCreateCall: ( - List safeArgNames, { - required String apiVarName, - }) { - return 'try instanceManager.removeAllObjects()'; - }, + onCreateCall: + (List safeArgNames, {required String apiVarName}) { + return 'try instanceManager.removeAllObjects()'; + }, ); }, ); @@ -1078,8 +1075,8 @@ if (wrapped == nil) { Root root, Indent indent, ) { - final Iterable allProxyApis = - root.apis.whereType(); + final Iterable allProxyApis = root.apis + .whereType(); _writeProxyApiRegistrar( indent, @@ -1289,8 +1286,9 @@ if (wrapped == nil) { final String swiftApiDelegateName = '${hostProxyApiPrefix}Delegate${api.name}'; - final String type = - api.hasMethodsRequiringImplementation() ? 'protocol' : 'open class'; + final String type = api.hasMethodsRequiringImplementation() + ? 'protocol' + : 'open class'; indent.writeScoped('$type $swiftApiDelegateName {', '}', () { _writeProxyApiConstructorDelegateMethods( indent, @@ -1716,10 +1714,9 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has (MapEntry e) => getEnumSafeArgumentExpression(e.key, e.value), ); - final String sendArgument = - parameters.isEmpty - ? 'nil' - : '[${enumSafeArgNames.join(', ')}] as [Any?]'; + final String sendArgument = parameters.isEmpty + ? 'nil' + : '[${enumSafeArgNames.join(', ')}] as [Any?]'; const String channel = 'channel'; indent.writeln('let channelName: String = "$channelName"'); indent.writeln( @@ -1768,11 +1765,11 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has // There is a swift bug with unwrapping maps of nullable Enums; final String enumMapForceUnwrap = returnType.baseName == 'Map' && - returnType.typeArguments.any( - (TypeDeclaration type) => type.isEnum, - ) - ? '!' - : ''; + returnType.typeArguments.any( + (TypeDeclaration type) => type.isEnum, + ) + ? '!' + : ''; indent.writeln('completion(.success(result$enumMapForceUnwrap))'); } }); @@ -1845,11 +1842,11 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has // There is a swift bug with unwrapping maps of nullable Enums; final String enumMapForceUnwrap = arg.type.baseName == 'Map' && - arg.type.typeArguments.any( - (TypeDeclaration type) => type.isEnum, - ) - ? '!' - : ''; + arg.type.typeArguments.any( + (TypeDeclaration type) => type.isEnum, + ) + ? '!' + : ''; _writeGenericCasting( indent: indent, @@ -1873,18 +1870,18 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has if (onCreateCall == null) { // Empty parens are not required when calling a method whose only // argument is a trailing closure. - final String argumentString = - methodArgument.isEmpty && isAsynchronous - ? '' - : '(${methodArgument.join(', ')})'; + final String argumentString = methodArgument.isEmpty && isAsynchronous + ? '' + : '(${methodArgument.join(', ')})'; call = '${tryStatement}api.${components.name}$argumentString'; } else { call = onCreateCall(methodArgument, apiVarName: 'api'); } if (isAsynchronous) { final String resultName = returnType.isVoid ? 'nil' : 'res'; - final String successVariableInit = - returnType.isVoid ? '' : '(let res)'; + final String successVariableInit = returnType.isVoid + ? '' + : '(let res)'; indent.write('$call '); indent.addScoped('{ result in', '}', () { @@ -2082,10 +2079,9 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has } final String methodSignature = _getMethodSignature( - name: - constructor.name.isNotEmpty - ? constructor.name - : 'pigeonDefaultConstructor', + name: constructor.name.isNotEmpty + ? constructor.name + : 'pigeonDefaultConstructor', parameters: [ Parameter( name: 'pigeonApi', @@ -2375,16 +2371,14 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has } for (final Constructor constructor in api.constructors) { - final String name = - constructor.name.isNotEmpty - ? constructor.name - : 'pigeonDefaultConstructor'; + final String name = constructor.name.isNotEmpty + ? constructor.name + : 'pigeonDefaultConstructor'; final String channelName = makeChannelNameWithStrings( apiName: api.name, - methodName: - constructor.name.isNotEmpty - ? constructor.name - : '${classMemberNamePrefix}defaultConstructor', + methodName: constructor.name.isNotEmpty + ? constructor.name + : '${classMemberNamePrefix}defaultConstructor', dartPackageName: dartPackageName, ); writeWithApiCheckIfNecessary( @@ -2403,19 +2397,20 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has returnType: const TypeDeclaration.voidDeclaration(), swiftFunction: null, isAsynchronous: false, - onCreateCall: ( - List methodParameters, { - required String apiVarName, - }) { - final List parameters = [ - 'pigeonApi: $apiVarName', - // Skip the identifier used by the InstanceManager. - ...methodParameters.skip(1), - ]; - return '$apiVarName.pigeonRegistrar.instanceManager.addDartCreatedInstance(\n' - 'try $apiVarName.pigeonDelegate.$name(${parameters.join(', ')}),\n' - 'withIdentifier: pigeonIdentifierArg)'; - }, + onCreateCall: + ( + List methodParameters, { + required String apiVarName, + }) { + final List parameters = [ + 'pigeonApi: $apiVarName', + // Skip the identifier used by the InstanceManager. + ...methodParameters.skip(1), + ]; + return '$apiVarName.pigeonRegistrar.instanceManager.addDartCreatedInstance(\n' + 'try $apiVarName.pigeonDelegate.$name(${parameters.join(', ')}),\n' + 'withIdentifier: pigeonIdentifierArg)'; + }, parameters: [ Parameter( name: 'pigeonIdentifier', @@ -2452,18 +2447,18 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has swiftFunction: null, isAsynchronous: false, returnType: const TypeDeclaration.voidDeclaration(), - onCreateCall: ( - List methodParameters, { - required String apiVarName, - }) { - final String instanceArg = - field.isStatic + onCreateCall: + ( + List methodParameters, { + required String apiVarName, + }) { + final String instanceArg = field.isStatic ? '' : ', pigeonInstance: pigeonInstanceArg'; - return '$apiVarName.pigeonRegistrar.instanceManager.addDartCreatedInstance(' - 'try $apiVarName.pigeonDelegate.${field.name}(pigeonApi: api$instanceArg), ' - 'withIdentifier: pigeonIdentifierArg)'; - }, + return '$apiVarName.pigeonRegistrar.instanceManager.addDartCreatedInstance(' + 'try $apiVarName.pigeonDelegate.${field.name}(pigeonApi: api$instanceArg), ' + 'withIdentifier: pigeonIdentifierArg)'; + }, parameters: [ if (!field.isStatic) Parameter( @@ -2505,20 +2500,22 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has returnType: method.returnType, isAsynchronous: method.isAsynchronous, swiftFunction: null, - onCreateCall: ( - List methodParameters, { - required String apiVarName, - }) { - final String tryStatement = - method.isAsynchronous ? '' : 'try '; - final List parameters = [ - 'pigeonApi: $apiVarName', - // Skip the identifier used by the InstanceManager. - ...methodParameters, - ]; - - return '$tryStatement$apiVarName.pigeonDelegate.${method.name}(${parameters.join(', ')})'; - }, + onCreateCall: + ( + List methodParameters, { + required String apiVarName, + }) { + final String tryStatement = method.isAsynchronous + ? '' + : 'try '; + final List parameters = [ + 'pigeonApi: $apiVarName', + // Skip the identifier used by the InstanceManager. + ...methodParameters, + ]; + + return '$tryStatement$apiVarName.pigeonDelegate.${method.name}(${parameters.join(', ')})'; + }, parameters: [ if (!method.isStatic) Parameter( @@ -2921,10 +2918,9 @@ String _getSafeArgumentName(int count, NamedType argument) { } String _camelCase(String text) { - final String pascal = - text.split('_').map((String part) { - return part.isEmpty ? '' : part[0].toUpperCase() + part.substring(1); - }).join(); + final String pascal = text.split('_').map((String part) { + return part.isEmpty ? '' : part[0].toUpperCase() + part.substring(1); + }).join(); return pascal[0].toLowerCase() + pascal.substring(1); } @@ -3021,8 +3017,9 @@ String _getMethodSignature({ returnType: returnType, swiftFunction: swiftFunction, ); - final String returnTypeString = - returnType.isVoid ? 'Void' : _nullSafeSwiftTypeForDartType(returnType); + final String returnTypeString = returnType.isVoid + ? 'Void' + : _nullSafeSwiftTypeForDartType(returnType); final Iterable types = parameters.map( (NamedType e) => _nullSafeSwiftTypeForDartType(e.type), @@ -3095,16 +3092,15 @@ class _SwiftFunctionComponents { return _SwiftFunctionComponents._( name: name, returnType: returnType, - arguments: - parameters - .map( - (NamedType field) => _SwiftFunctionArgument( - name: field.name, - type: field.type, - namedType: field, - ), - ) - .toList(), + arguments: parameters + .map( + (NamedType field) => _SwiftFunctionArgument( + name: field.name, + type: field.type, + namedType: field, + ), + ) + .toList(), ); } @@ -3112,27 +3108,23 @@ class _SwiftFunctionComponents { final RegExp signatureRegex = RegExp(r'(\w+) *\(' + argsExtractor + r'\)'); final RegExpMatch match = signatureRegex.firstMatch(swiftFunction)!; - final Iterable labels = - match - .groups( - List.generate(parameters.length, (int index) => index + 2), - ) - .whereType(); + final Iterable labels = match + .groups(List.generate(parameters.length, (int index) => index + 2)) + .whereType(); return _SwiftFunctionComponents._( name: match.group(1)!, returnType: returnType, - arguments: - map2( - parameters, - labels, - (NamedType field, String label) => _SwiftFunctionArgument( - name: field.name, - label: label == field.name ? null : label, - type: field.type, - namedType: field, - ), - ).toList(), + arguments: map2( + parameters, + labels, + (NamedType field, String label) => _SwiftFunctionArgument( + name: field.name, + label: label == field.name ? null : label, + type: field.type, + namedType: field, + ), + ).toList(), ); } diff --git a/packages/pigeon/lib/src/swift/templates.dart b/packages/pigeon/lib/src/swift/templates.dart index 03ddee44aa6..35266a2944c 100644 --- a/packages/pigeon/lib/src/swift/templates.dart +++ b/packages/pigeon/lib/src/swift/templates.dart @@ -34,7 +34,8 @@ protocol ${instanceManagerFinalizerDelegateName(options)}: AnyObject { '''; /// Template for an object that tracks when an object is deallocated. -String instanceManagerFinalizerTemplate(InternalSwiftOptions options) => ''' +String instanceManagerFinalizerTemplate(InternalSwiftOptions options) => + ''' // Attaches to an object to receive a callback when the object is deallocated. internal final class ${_instanceManagerFinalizerName(options)} { internal static let associatedObjectKey = malloc(1)! diff --git a/packages/pigeon/pubspec.yaml b/packages/pigeon/pubspec.yaml index d9114129958..5dde01163aa 100644 --- a/packages/pigeon/pubspec.yaml +++ b/packages/pigeon/pubspec.yaml @@ -5,7 +5,7 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 26.1.0 # This must match the version in lib/src/generator_tools.dart environment: - sdk: ^3.7.0 + sdk: ^3.8.0 dependencies: analyzer: ">=6.0.0 <9.0.0" diff --git a/packages/pigeon/test/dart_generator_test.dart b/packages/pigeon/test/dart_generator_test.dart index 30c7dca3212..f159cdaf48d 100644 --- a/packages/pigeon/test/dart_generator_test.dart +++ b/packages/pigeon/test/dart_generator_test.dart @@ -63,7 +63,10 @@ void main() { test('gen one enum', () { final Enum anEnum = Enum( name: 'Foobar', - members: [EnumMember(name: 'one'), EnumMember(name: 'two')], + members: [ + EnumMember(name: 'one'), + EnumMember(name: 'two'), + ], ); final Root root = Root( apis: [], diff --git a/packages/pigeon/test/functional_test.dart b/packages/pigeon/test/functional_test.dart index b4c38bd5e96..4e83c21031e 100644 --- a/packages/pigeon/test/functional_test.dart +++ b/packages/pigeon/test/functional_test.dart @@ -8,11 +8,10 @@ import 'package:test/test.dart'; void main() { test('indexMap', () { final List items = ['a', 'b', 'c']; - final List result = - indexMap( - items, - (int index, String value) => value + index.toString(), - ).toList(); + final List result = indexMap( + items, + (int index, String value) => value + index.toString(), + ).toList(); expect(result[0], 'a0'); expect(result[1], 'b1'); expect(result[2], 'c2'); @@ -37,8 +36,11 @@ void main() { }); test('map2', () { - final List result = - map2([3, 5, 7], [1, 2, 3], (int x, int y) => x * y).toList(); + final List result = map2( + [3, 5, 7], + [1, 2, 3], + (int x, int y) => x * y, + ).toList(); expect(result[0], 3); expect(result[1], 10); expect(result[2], 21); @@ -52,12 +54,11 @@ void main() { }); test('map3', () { - final List result = - map3([3, 5, 7], [1, 2, 3], [ - 2, - 2, - 2, - ], (int x, int y, int z) => x * y * z).toList(); + final List result = map3([3, 5, 7], [1, 2, 3], [ + 2, + 2, + 2, + ], (int x, int y, int z) => x * y * z).toList(); expect(result[0], 6); expect(result[1], 20); expect(result[2], 42); @@ -65,13 +66,12 @@ void main() { test('map3 unequal', () { expect( - () => - map3( - [], - [1, 2, 3], - [], - (int x, int y, int z) => x * y * z, - ).toList(), + () => map3( + [], + [1, 2, 3], + [], + (int x, int y, int z) => x * y * z, + ).toList(), throwsArgumentError, ); }); diff --git a/packages/pigeon/test/gobject_generator_test.dart b/packages/pigeon/test/gobject_generator_test.dart index aca83f4c99b..2c66b13afe0 100644 --- a/packages/pigeon/test/gobject_generator_test.dart +++ b/packages/pigeon/test/gobject_generator_test.dart @@ -954,7 +954,10 @@ void main() { final Class objectClass = Class(name: 'Object', fields: []); final Enum anEnum = Enum( name: 'enum', - members: [EnumMember(name: 'one'), EnumMember(name: 'two')], + members: [ + EnumMember(name: 'one'), + EnumMember(name: 'two'), + ], ); final Root root = Root( apis: [ diff --git a/packages/pigeon/test/kotlin_generator_test.dart b/packages/pigeon/test/kotlin_generator_test.dart index cda740ae734..0196ca85923 100644 --- a/packages/pigeon/test/kotlin_generator_test.dart +++ b/packages/pigeon/test/kotlin_generator_test.dart @@ -61,7 +61,10 @@ void main() { test('gen one enum', () { final Enum anEnum = Enum( name: 'Foobar', - members: [EnumMember(name: 'one'), EnumMember(name: 'two')], + members: [ + EnumMember(name: 'one'), + EnumMember(name: 'two'), + ], ); final Root root = Root( apis: [], diff --git a/packages/pigeon/test/objc_generator_test.dart b/packages/pigeon/test/objc_generator_test.dart index 41b51562209..2c806907828 100644 --- a/packages/pigeon/test/objc_generator_test.dart +++ b/packages/pigeon/test/objc_generator_test.dart @@ -3883,7 +3883,10 @@ void main() { test('header of FlutterApi uses correct enum name with prefix', () { final Enum enum1 = Enum( name: 'Enum1', - members: [EnumMember(name: 'one'), EnumMember(name: 'two')], + members: [ + EnumMember(name: 'one'), + EnumMember(name: 'two'), + ], ); final Root root = Root( apis: [ @@ -3933,7 +3936,10 @@ void main() { test('source of FlutterApi uses correct enum name with prefix', () { final Enum enum1 = Enum( name: 'Enum1', - members: [EnumMember(name: 'one'), EnumMember(name: 'two')], + members: [ + EnumMember(name: 'one'), + EnumMember(name: 'two'), + ], ); final Root root = Root( apis: [ @@ -3983,7 +3989,10 @@ void main() { test('header of HostApi uses correct enum name with prefix', () { final Enum enum1 = Enum( name: 'Enum1', - members: [EnumMember(name: 'one'), EnumMember(name: 'two')], + members: [ + EnumMember(name: 'one'), + EnumMember(name: 'two'), + ], ); final TypeDeclaration enumType = TypeDeclaration( baseName: 'Enum1', @@ -4034,7 +4043,10 @@ void main() { test('source of HostApi uses correct enum name with prefix', () { final Enum enum1 = Enum( name: 'Enum1', - members: [EnumMember(name: 'one'), EnumMember(name: 'two')], + members: [ + EnumMember(name: 'one'), + EnumMember(name: 'two'), + ], ); final TypeDeclaration enumType = TypeDeclaration( baseName: 'Enum1', diff --git a/packages/pigeon/test/pigeon_lib_test.dart b/packages/pigeon/test/pigeon_lib_test.dart index 420b34b6d3d..b2409c4dbc5 100644 --- a/packages/pigeon/test/pigeon_lib_test.dart +++ b/packages/pigeon/test/pigeon_lib_test.dart @@ -472,8 +472,9 @@ abstract class NestorApi { final ParseResults results = parseSource(code); expect(results.errors.length, 0); expect(results.root.apis.length, 1); - final List classNames = - results.root.classes.map((Class x) => x.name).toList(); + final List classNames = results.root.classes + .map((Class x) => x.name) + .toList(); expect(classNames.length, 2); expect(classNames.contains('Nestor'), true); expect(classNames.contains('OnlyVisibleFromNesting'), true); diff --git a/packages/pigeon/test/swift_generator_test.dart b/packages/pigeon/test/swift_generator_test.dart index 4344b203ae5..d30cd8ae4ed 100644 --- a/packages/pigeon/test/swift_generator_test.dart +++ b/packages/pigeon/test/swift_generator_test.dart @@ -64,7 +64,10 @@ void main() { test('gen one enum', () { final Enum anEnum = Enum( name: 'Foobar', - members: [EnumMember(name: 'one'), EnumMember(name: 'two')], + members: [ + EnumMember(name: 'one'), + EnumMember(name: 'two'), + ], ); final Root root = Root( apis: [], @@ -872,7 +875,10 @@ void main() { test('gen one enum class', () { final Enum anEnum = Enum( name: 'Enum1', - members: [EnumMember(name: 'one'), EnumMember(name: 'two')], + members: [ + EnumMember(name: 'one'), + EnumMember(name: 'two'), + ], ); final Class classDefinition = Class( name: 'EnumClass', diff --git a/packages/pigeon/tool/generate.dart b/packages/pigeon/tool/generate.dart index 5c7b4c703f3..b32381eb09b 100644 --- a/packages/pigeon/tool/generate.dart +++ b/packages/pigeon/tool/generate.dart @@ -28,40 +28,39 @@ const String _overflowFiller = 'overflow'; const List _fileGroups = [_test, _example]; Future main(List args) async { - final ArgParser parser = - ArgParser() - ..addFlag( - _formatFlag, - abbr: 'f', - help: - 'Autoformat after generation. This flag is no longer needed, as this behavior is the default', - defaultsTo: true, - hide: true, - ) - ..addFlag( - _noFormatFlag, - abbr: 'n', - help: 'Do not autoformat after generation.', - ) - ..addFlag( - _helpFlag, - negatable: false, - abbr: 'h', - help: 'Print this reference.', - ) - ..addFlag( - _overflowFiller, - abbr: 'o', - help: - 'Injects 120 Enums into the pigeon ast, used for testing overflow utilities.', - hide: true, - ) - ..addMultiOption( - _files, - help: - 'Select specific groups of files to generate; $_test or $_example. Defaults to both.', - allowed: _fileGroups, - ); + final ArgParser parser = ArgParser() + ..addFlag( + _formatFlag, + abbr: 'f', + help: + 'Autoformat after generation. This flag is no longer needed, as this behavior is the default', + defaultsTo: true, + hide: true, + ) + ..addFlag( + _noFormatFlag, + abbr: 'n', + help: 'Do not autoformat after generation.', + ) + ..addFlag( + _helpFlag, + negatable: false, + abbr: 'h', + help: 'Print this reference.', + ) + ..addFlag( + _overflowFiller, + abbr: 'o', + help: + 'Injects 120 Enums into the pigeon ast, used for testing overflow utilities.', + hide: true, + ) + ..addMultiOption( + _files, + help: + 'Select specific groups of files to generate; $_test or $_example. Defaults to both.', + allowed: _fileGroups, + ); final ArgResults argResults = parser.parse(args); if (argResults.wasParsed(_helpFlag)) { @@ -76,10 +75,9 @@ ${parser.usage}'''); final bool includeOverflow = argResults.wasParsed(_overflowFiller); - final List toGenerate = - argResults.wasParsed(_files) - ? argResults[_files] as List - : _fileGroups; + final List toGenerate = argResults.wasParsed(_files) + ? argResults[_files] as List + : _fileGroups; if (toGenerate.contains(_test)) { print('Generating platform_test/ output...'); diff --git a/packages/pigeon/tool/run_tests.dart b/packages/pigeon/tool/run_tests.dart index 54146d15403..b0885d01b59 100644 --- a/packages/pigeon/tool/run_tests.dart +++ b/packages/pigeon/tool/run_tests.dart @@ -114,11 +114,10 @@ Future _validateGeneratedFiles( repositoryRoot: repositoryRoot, relativePigeonPath: relativePigeonPath, ); - final Set extensions = - languagesToValidate - .map((GeneratorLanguage lang) => _extensionsForLanguage(lang)) - .flattened - .toSet(); + final Set extensions = languagesToValidate + .map((GeneratorLanguage lang) => _extensionsForLanguage(lang)) + .flattened + .toSet(); final Iterable filteredFiles = modifiedFiles.where( (String path) => extensions.contains(p.extension(path).replaceFirst('.', '')), diff --git a/packages/pigeon/tool/shared/generation.dart b/packages/pigeon/tool/shared/generation.dart index e72da975794..48ee3daf16a 100644 --- a/packages/pigeon/tool/shared/generation.dart +++ b/packages/pigeon/tool/shared/generation.dart @@ -118,61 +118,54 @@ Future generateTestPigeons({ final bool kotlinErrorClassGenerationTestFiles = input == 'core_tests' || input == 'primitive'; - final String kotlinErrorName = - kotlinErrorClassGenerationTestFiles - ? 'FlutterError' - : '${pascalCaseName}Error'; + final String kotlinErrorName = kotlinErrorClassGenerationTestFiles + ? 'FlutterError' + : '${pascalCaseName}Error'; final bool swiftErrorUseDefaultErrorName = input == 'core_tests' || input == 'primitive'; - final String? swiftErrorClassName = - swiftErrorUseDefaultErrorName ? null : '${pascalCaseName}Error'; + final String? swiftErrorClassName = swiftErrorUseDefaultErrorName + ? null + : '${pascalCaseName}Error'; // Generate the default language test plugin output. int generateCode = await runPigeon( input: './pigeons/$input.dart', dartOut: '$sharedDartOutputBase/lib/src/generated/$input.gen.dart', - dartTestOut: - input == 'message' - ? '$sharedDartOutputBase/test/test_message.gen.dart' - : null, + dartTestOut: input == 'message' + ? '$sharedDartOutputBase/test/test_message.gen.dart' + : null, dartPackageName: 'pigeon_integration_tests', suppressVersion: true, // Android - kotlinOut: - skipLanguages.contains(GeneratorLanguage.kotlin) - ? null - : '$outputBase/android/src/main/kotlin/com/example/test_plugin/$pascalCaseName.gen.kt', + kotlinOut: skipLanguages.contains(GeneratorLanguage.kotlin) + ? null + : '$outputBase/android/src/main/kotlin/com/example/test_plugin/$pascalCaseName.gen.kt', kotlinPackage: 'com.example.test_plugin', kotlinErrorClassName: kotlinErrorName, kotlinIncludeErrorClass: input != 'primitive', // iOS/macOS - swiftOut: - skipLanguages.contains(GeneratorLanguage.swift) - ? null - : '$outputBase/darwin/$testPluginName/Sources/$testPluginName/$pascalCaseName.gen.swift', + swiftOut: skipLanguages.contains(GeneratorLanguage.swift) + ? null + : '$outputBase/darwin/$testPluginName/Sources/$testPluginName/$pascalCaseName.gen.swift', swiftErrorClassName: swiftErrorClassName, swiftIncludeErrorClass: input != 'primitive', // Linux - gobjectHeaderOut: - skipLanguages.contains(GeneratorLanguage.gobject) - ? null - : '$outputBase/linux/pigeon/$input.gen.h', - gobjectSourceOut: - skipLanguages.contains(GeneratorLanguage.gobject) - ? null - : '$outputBase/linux/pigeon/$input.gen.cc', + gobjectHeaderOut: skipLanguages.contains(GeneratorLanguage.gobject) + ? null + : '$outputBase/linux/pigeon/$input.gen.h', + gobjectSourceOut: skipLanguages.contains(GeneratorLanguage.gobject) + ? null + : '$outputBase/linux/pigeon/$input.gen.cc', gobjectModule: '${pascalCaseName}PigeonTest', // Windows - cppHeaderOut: - skipLanguages.contains(GeneratorLanguage.cpp) - ? null - : '$outputBase/windows/pigeon/$input.gen.h', - cppSourceOut: - skipLanguages.contains(GeneratorLanguage.cpp) - ? null - : '$outputBase/windows/pigeon/$input.gen.cpp', + cppHeaderOut: skipLanguages.contains(GeneratorLanguage.cpp) + ? null + : '$outputBase/windows/pigeon/$input.gen.h', + cppSourceOut: skipLanguages.contains(GeneratorLanguage.cpp) + ? null + : '$outputBase/windows/pigeon/$input.gen.cpp', cppNamespace: '${input}_pigeontest', injectOverflowTypes: includeOverflow && input == 'core_tests', ); @@ -190,28 +183,24 @@ Future generateTestPigeons({ // Android // This doesn't use the '.gen' suffix since Java has strict file naming // rules. - javaOut: - skipLanguages.contains(GeneratorLanguage.java) - ? null - : '$alternateOutputBase/android/src/main/java/com/example/' - 'alternate_language_test_plugin/${_javaFilenameForName(input)}.java', + javaOut: skipLanguages.contains(GeneratorLanguage.java) + ? null + : '$alternateOutputBase/android/src/main/java/com/example/' + 'alternate_language_test_plugin/${_javaFilenameForName(input)}.java', javaPackage: 'com.example.alternate_language_test_plugin', // iOS/macOS - objcHeaderOut: - skipLanguages.contains(GeneratorLanguage.objc) - ? null - : '$objcBase/$objcBaseRelativeHeaderPath', - objcSourceOut: - skipLanguages.contains(GeneratorLanguage.objc) - ? null - : '$objcBase/$pascalCaseName.gen.m', + objcHeaderOut: skipLanguages.contains(GeneratorLanguage.objc) + ? null + : '$objcBase/$objcBaseRelativeHeaderPath', + objcSourceOut: skipLanguages.contains(GeneratorLanguage.objc) + ? null + : '$objcBase/$pascalCaseName.gen.m', objcHeaderIncludePath: './$objcBaseRelativeHeaderPath', - objcPrefix: - input == 'core_tests' - ? 'FLT' - : input == 'enum' - ? 'PGN' - : '', + objcPrefix: input == 'core_tests' + ? 'FLT' + : input == 'enum' + ? 'PGN' + : '', suppressVersion: true, dartPackageName: 'pigeon_integration_tests', injectOverflowTypes: includeOverflow && input == 'core_tests', @@ -295,8 +284,9 @@ Future runPigeon({ cppOptions: CppOptions(namespace: cppNamespace), gobjectHeaderOut: injectOverflowTypes ? null : gobjectHeaderOut, gobjectSourceOut: injectOverflowTypes ? null : gobjectSourceOut, - gobjectOptions: - injectOverflowTypes ? null : GObjectOptions(module: gobjectModule), + gobjectOptions: injectOverflowTypes + ? null + : GObjectOptions(module: gobjectModule), javaOut: javaOut, javaOptions: JavaOptions(package: javaPackage), kotlinOut: kotlinOut, diff --git a/packages/pigeon/tool/shared/process_utils.dart b/packages/pigeon/tool/shared/process_utils.dart index 8d5e54b35d0..2055ecd4fec 100644 --- a/packages/pigeon/tool/shared/process_utils.dart +++ b/packages/pigeon/tool/shared/process_utils.dart @@ -16,8 +16,9 @@ Future runProcess( command, arguments, workingDirectory: workingDirectory, - mode: - streamOutput ? ProcessStartMode.inheritStdio : ProcessStartMode.normal, + mode: streamOutput + ? ProcessStartMode.inheritStdio + : ProcessStartMode.normal, ); if (streamOutput) { diff --git a/packages/pigeon/tool/test.dart b/packages/pigeon/tool/test.dart index b274d97bb98..5754778c191 100644 --- a/packages/pigeon/tool/test.dart +++ b/packages/pigeon/tool/test.dart @@ -26,42 +26,37 @@ const String _format = 'format'; const String _overflow = 'overflow'; Future main(List args) async { - final ArgParser parser = - ArgParser() - ..addMultiOption( - _testFlag, - abbr: 't', - help: 'Only run specified tests.', - ) - ..addFlag( - _noGen, - abbr: 'g', - help: 'Skips the generation step.', - negatable: false, - ) - ..addFlag( - _format, - abbr: 'f', - help: 'Formats generated test files before running tests.', - ) - ..addFlag( - _overflow, - help: - 'Generates overflow files for integration tests, runs tests with and without overflow files.', - abbr: 'o', - ) - ..addFlag( - _listFlag, - negatable: false, - abbr: 'l', - help: 'List available tests.', - ) - ..addFlag( - 'help', - negatable: false, - abbr: 'h', - help: 'Print this reference.', - ); + final ArgParser parser = ArgParser() + ..addMultiOption(_testFlag, abbr: 't', help: 'Only run specified tests.') + ..addFlag( + _noGen, + abbr: 'g', + help: 'Skips the generation step.', + negatable: false, + ) + ..addFlag( + _format, + abbr: 'f', + help: 'Formats generated test files before running tests.', + ) + ..addFlag( + _overflow, + help: + 'Generates overflow files for integration tests, runs tests with and without overflow files.', + abbr: 'o', + ) + ..addFlag( + _listFlag, + negatable: false, + abbr: 'l', + help: 'List available tests.', + ) + ..addFlag( + 'help', + negatable: false, + abbr: 'h', + help: 'Print this reference.', + ); final ArgResults argResults = parser.parse(args); List testsToRun = []; diff --git a/packages/plugin_platform_interface/CHANGELOG.md b/packages/plugin_platform_interface/CHANGELOG.md index e5dbb81d85b..d4f0629c966 100644 --- a/packages/plugin_platform_interface/CHANGELOG.md +++ b/packages/plugin_platform_interface/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 2.1.8 diff --git a/packages/plugin_platform_interface/pubspec.yaml b/packages/plugin_platform_interface/pubspec.yaml index 7c850f65faf..d94551ea384 100644 --- a/packages/plugin_platform_interface/pubspec.yaml +++ b/packages/plugin_platform_interface/pubspec.yaml @@ -18,7 +18,7 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.1.8 environment: - sdk: ^3.7.0 + sdk: ^3.8.0 dependencies: meta: ^1.3.0 diff --git a/packages/pointer_interceptor/pointer_interceptor/CHANGELOG.md b/packages/pointer_interceptor/pointer_interceptor/CHANGELOG.md index e684b840f44..3f8575892ef 100644 --- a/packages/pointer_interceptor/pointer_interceptor/CHANGELOG.md +++ b/packages/pointer_interceptor/pointer_interceptor/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 0.10.1+2 diff --git a/packages/pointer_interceptor/pointer_interceptor/example/lib/platforms/native_widget_web.dart b/packages/pointer_interceptor/pointer_interceptor/example/lib/platforms/native_widget_web.dart index 854445f55a8..7ee8d11aa89 100644 --- a/packages/pointer_interceptor/pointer_interceptor/example/lib/platforms/native_widget_web.dart +++ b/packages/pointer_interceptor/pointer_interceptor/example/lib/platforms/native_widget_web.dart @@ -8,13 +8,12 @@ import 'dart:ui_web' as ui_web; import 'package:flutter/material.dart'; /// The html.Element that will be rendered underneath the flutter UI. -html.Element htmlElement = - html.DivElement() - ..style.width = '100%' - ..style.height = '100%' - ..style.backgroundColor = '#fabada' - ..style.cursor = 'auto' - ..id = 'background-html-view'; +html.Element htmlElement = html.DivElement() + ..style.width = '100%' + ..style.height = '100%' + ..style.backgroundColor = '#fabada' + ..style.cursor = 'auto' + ..id = 'background-html-view'; // See other examples commented out below... diff --git a/packages/pointer_interceptor/pointer_interceptor/example/pubspec.yaml b/packages/pointer_interceptor/pointer_interceptor/example/pubspec.yaml index 37ee177731a..0d88e88744d 100644 --- a/packages/pointer_interceptor/pointer_interceptor/example/pubspec.yaml +++ b/packages/pointer_interceptor/pointer_interceptor/example/pubspec.yaml @@ -4,8 +4,8 @@ publish_to: 'none' version: 1.0.0 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/pointer_interceptor/pointer_interceptor/pubspec.yaml b/packages/pointer_interceptor/pointer_interceptor/pubspec.yaml index edc465003a9..b5a5a6c181b 100644 --- a/packages/pointer_interceptor/pointer_interceptor/pubspec.yaml +++ b/packages/pointer_interceptor/pointer_interceptor/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 0.10.1+2 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" flutter: plugin: diff --git a/packages/pointer_interceptor/pointer_interceptor_platform_interface/CHANGELOG.md b/packages/pointer_interceptor/pointer_interceptor_platform_interface/CHANGELOG.md index d10ca7524b0..00109ecd115 100644 --- a/packages/pointer_interceptor/pointer_interceptor_platform_interface/CHANGELOG.md +++ b/packages/pointer_interceptor/pointer_interceptor_platform_interface/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 0.10.0+1 diff --git a/packages/pointer_interceptor/pointer_interceptor_platform_interface/pubspec.yaml b/packages/pointer_interceptor/pointer_interceptor_platform_interface/pubspec.yaml index 604062d901a..7606f2a7ae1 100644 --- a/packages/pointer_interceptor/pointer_interceptor_platform_interface/pubspec.yaml +++ b/packages/pointer_interceptor/pointer_interceptor_platform_interface/pubspec.yaml @@ -6,8 +6,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 0.10.0+1 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/pointer_interceptor/pointer_interceptor_web/CHANGELOG.md b/packages/pointer_interceptor/pointer_interceptor_web/CHANGELOG.md index 7af1c73a4c2..7df220e9fd0 100644 --- a/packages/pointer_interceptor/pointer_interceptor_web/CHANGELOG.md +++ b/packages/pointer_interceptor/pointer_interceptor_web/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 0.10.3 diff --git a/packages/pointer_interceptor/pointer_interceptor_web/example/integration_test/widget_test.dart b/packages/pointer_interceptor/pointer_interceptor_web/example/integration_test/widget_test.dart index 7a3ba4656d2..77cff645976 100644 --- a/packages/pointer_interceptor/pointer_interceptor_web/example/integration_test/widget_test.dart +++ b/packages/pointer_interceptor/pointer_interceptor_web/example/integration_test/widget_test.dart @@ -129,8 +129,9 @@ web.Element _getHtmlElementAt(Offset point) { // Probe at the shadow so the browser reports semantics nodes in addition to // platform view elements. If probed from `html.document` the browser hides // the contents of as an implementation detail. - final web.ShadowRoot glassPaneShadow = - web.document.querySelector('flt-glass-pane')!.shadowRoot!; + final web.ShadowRoot glassPaneShadow = web.document + .querySelector('flt-glass-pane')! + .shadowRoot!; // Use `round` below to ensure clicks always fall *inside* the located // element, rather than truncating the decimals. // Truncating decimals makes some tests fail when a centered element (in high diff --git a/packages/pointer_interceptor/pointer_interceptor_web/example/pubspec.yaml b/packages/pointer_interceptor/pointer_interceptor_web/example/pubspec.yaml index b2361de7c2d..7e26f72ebab 100644 --- a/packages/pointer_interceptor/pointer_interceptor_web/example/pubspec.yaml +++ b/packages/pointer_interceptor/pointer_interceptor_web/example/pubspec.yaml @@ -3,8 +3,8 @@ description: "Demonstrates how to use the pointer_interceptor_web plugin." publish_to: 'none' environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: cupertino_icons: ^1.0.2 diff --git a/packages/pointer_interceptor/pointer_interceptor_web/pubspec.yaml b/packages/pointer_interceptor/pointer_interceptor_web/pubspec.yaml index 338da340227..0e3204ba346 100644 --- a/packages/pointer_interceptor/pointer_interceptor_web/pubspec.yaml +++ b/packages/pointer_interceptor/pointer_interceptor_web/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 0.10.3 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" flutter: plugin: diff --git a/packages/quick_actions/quick_actions/CHANGELOG.md b/packages/quick_actions/quick_actions/CHANGELOG.md index 127c8162e8f..44eff9160de 100644 --- a/packages/quick_actions/quick_actions/CHANGELOG.md +++ b/packages/quick_actions/quick_actions/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. * Updates README to indicate that Andoid SDK <21 is no longer supported. ## 1.1.0 diff --git a/packages/quick_actions/quick_actions/example/pubspec.yaml b/packages/quick_actions/quick_actions/example/pubspec.yaml index 1803e2aecbc..198113858ff 100644 --- a/packages/quick_actions/quick_actions/example/pubspec.yaml +++ b/packages/quick_actions/quick_actions/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the quick_actions plugin. publish_to: none environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/quick_actions/quick_actions/pubspec.yaml b/packages/quick_actions/quick_actions/pubspec.yaml index 0ed48370198..9802bb0a0b8 100644 --- a/packages/quick_actions/quick_actions/pubspec.yaml +++ b/packages/quick_actions/quick_actions/pubspec.yaml @@ -6,8 +6,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 1.1.0 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" flutter: plugin: diff --git a/packages/quick_actions/quick_actions_android/CHANGELOG.md b/packages/quick_actions/quick_actions_android/CHANGELOG.md index cd0049eb5cd..7e711da2c86 100644 --- a/packages/quick_actions/quick_actions_android/CHANGELOG.md +++ b/packages/quick_actions/quick_actions_android/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. + ## 1.0.25 * Resolves Gradle 9 deprecations. diff --git a/packages/quick_actions/quick_actions_android/example/pubspec.yaml b/packages/quick_actions/quick_actions_android/example/pubspec.yaml index db0dfa6472a..697dcba0993 100644 --- a/packages/quick_actions/quick_actions_android/example/pubspec.yaml +++ b/packages/quick_actions/quick_actions_android/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the quick_actions plugin. publish_to: none environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/quick_actions/quick_actions_platform_interface/CHANGELOG.md b/packages/quick_actions/quick_actions_platform_interface/CHANGELOG.md index dc43898e11a..c3f5df9627b 100644 --- a/packages/quick_actions/quick_actions_platform_interface/CHANGELOG.md +++ b/packages/quick_actions/quick_actions_platform_interface/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 1.1.0 diff --git a/packages/quick_actions/quick_actions_platform_interface/lib/method_channel/method_channel_quick_actions.dart b/packages/quick_actions/quick_actions_platform_interface/lib/method_channel/method_channel_quick_actions.dart index 15a782fcf68..3cbdba1b705 100644 --- a/packages/quick_actions/quick_actions_platform_interface/lib/method_channel/method_channel_quick_actions.dart +++ b/packages/quick_actions/quick_actions_platform_interface/lib/method_channel/method_channel_quick_actions.dart @@ -34,8 +34,9 @@ class MethodChannelQuickActions extends QuickActionsPlatform { @override Future setShortcutItems(List items) async { - final List> itemsList = - items.map(_serializeItem).toList(); + final List> itemsList = items + .map(_serializeItem) + .toList(); await channel.invokeMethod('setShortcutItems', itemsList); } diff --git a/packages/quick_actions/quick_actions_platform_interface/pubspec.yaml b/packages/quick_actions/quick_actions_platform_interface/pubspec.yaml index 5e932dd8957..cafba50c7bf 100644 --- a/packages/quick_actions/quick_actions_platform_interface/pubspec.yaml +++ b/packages/quick_actions/quick_actions_platform_interface/pubspec.yaml @@ -7,8 +7,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 1.1.0 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/rfw/CHANGELOG.md b/packages/rfw/CHANGELOG.md index 02234a2b447..776aedd5b02 100644 --- a/packages/rfw/CHANGELOG.md +++ b/packages/rfw/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. * Removes the wasm example. ## 1.0.31 diff --git a/packages/rfw/example/hello/pubspec.yaml b/packages/rfw/example/hello/pubspec.yaml index 83c7475ee70..f9a5e447232 100644 --- a/packages/rfw/example/hello/pubspec.yaml +++ b/packages/rfw/example/hello/pubspec.yaml @@ -4,8 +4,8 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev version: 1.0.0+1 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/rfw/example/local/pubspec.yaml b/packages/rfw/example/local/pubspec.yaml index 4bd596c8775..f751512ae14 100644 --- a/packages/rfw/example/local/pubspec.yaml +++ b/packages/rfw/example/local/pubspec.yaml @@ -4,8 +4,8 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev version: 1.0.0+1 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/rfw/example/remote/pubspec.yaml b/packages/rfw/example/remote/pubspec.yaml index 47cdb0e225b..10bc4dd89c9 100644 --- a/packages/rfw/example/remote/pubspec.yaml +++ b/packages/rfw/example/remote/pubspec.yaml @@ -4,8 +4,8 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev version: 1.0.0+1 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/rfw/pubspec.yaml b/packages/rfw/pubspec.yaml index 574faad5ee1..07270b3250d 100644 --- a/packages/rfw/pubspec.yaml +++ b/packages/rfw/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 1.0.31 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/rfw/test/material_widgets_test.dart b/packages/rfw/test/material_widgets_test.dart index f11f1e5e96d..e227b416cdf 100644 --- a/packages/rfw/test/material_widgets_test.dart +++ b/packages/rfw/test/material_widgets_test.dart @@ -27,10 +27,9 @@ void main() { const LibraryName testName = LibraryName(['test']); Runtime setupRuntime() { - final Runtime runtime = - Runtime() - ..update(coreName, createCoreWidgets()) - ..update(materialName, createMaterialWidgets()); + final Runtime runtime = Runtime() + ..update(coreName, createCoreWidgets()) + ..update(materialName, createMaterialWidgets()); addTearDown(runtime.dispose); return runtime; } diff --git a/packages/rfw/test/remote_widget_test.dart b/packages/rfw/test/remote_widget_test.dart index 5ec03353d58..b9f075e8ace 100644 --- a/packages/rfw/test/remote_widget_test.dart +++ b/packages/rfw/test/remote_widget_test.dart @@ -9,27 +9,25 @@ import 'package:rfw/rfw.dart'; void main() { testWidgets('RemoteWidget', (WidgetTester tester) async { - final Runtime runtime1 = - Runtime() - ..update(const LibraryName(['core']), createCoreWidgets()) - ..update( - const LibraryName(['test']), - parseLibraryFile(''' + final Runtime runtime1 = Runtime() + ..update(const LibraryName(['core']), createCoreWidgets()) + ..update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Placeholder(); '''), - ); + ); addTearDown(runtime1.dispose); - final Runtime runtime2 = - Runtime() - ..update(const LibraryName(['core']), createCoreWidgets()) - ..update( - const LibraryName(['test']), - parseLibraryFile(''' + final Runtime runtime2 = Runtime() + ..update(const LibraryName(['core']), createCoreWidgets()) + ..update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Container(); '''), - ); + ); addTearDown(runtime2.dispose); final DynamicContent data = DynamicContent(); await tester.pumpWidget( diff --git a/packages/rfw/test_coverage/bin/test_coverage.dart b/packages/rfw/test_coverage/bin/test_coverage.dart index d76bb52e84a..15bb2ee8613 100644 --- a/packages/rfw/test_coverage/bin/test_coverage.dart +++ b/packages/rfw/test_coverage/bin/test_coverage.dart @@ -80,12 +80,11 @@ Future main(List arguments) async { exit(0); } - final List libFiles = - Directory('lib') - .listSync(recursive: true) - .whereType() - .where((File file) => file.path.endsWith('.dart')) - .toList(); + final List libFiles = Directory('lib') + .listSync(recursive: true) + .whereType() + .where((File file) => file.path.endsWith('.dart')) + .toList(); final Set flakyLines = {}; final Set deadLines = {}; for (final File file in libFiles) { diff --git a/packages/rfw/test_coverage/pubspec.yaml b/packages/rfw/test_coverage/pubspec.yaml index 0e18f5a2842..62c2f2f84e5 100644 --- a/packages/rfw/test_coverage/pubspec.yaml +++ b/packages/rfw/test_coverage/pubspec.yaml @@ -4,7 +4,7 @@ version: 1.0.0 publish_to: none environment: - sdk: ^3.7.0 + sdk: ^3.8.0 dependencies: lcov_parser: 0.1.1 diff --git a/packages/shared_preferences/shared_preferences/CHANGELOG.md b/packages/shared_preferences/shared_preferences/CHANGELOG.md index 75ba4d952bf..252cb6c785c 100644 --- a/packages/shared_preferences/shared_preferences/CHANGELOG.md +++ b/packages/shared_preferences/shared_preferences/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. * Updates README to indicate that Andoid SDK <21 is no longer supported. ## 2.5.3 diff --git a/packages/shared_preferences/shared_preferences/example/lib/main.dart b/packages/shared_preferences/shared_preferences/example/lib/main.dart index 8d55b9f6645..a51bb141762 100644 --- a/packages/shared_preferences/shared_preferences/example/lib/main.dart +++ b/packages/shared_preferences/shared_preferences/example/lib/main.dart @@ -103,27 +103,26 @@ class SharedPreferencesDemoState extends State { body: Center( child: _WaitForInitialization( initialized: _preferencesReady.future, - builder: - (BuildContext context) => FutureBuilder( - future: _counter, - builder: (BuildContext context, AsyncSnapshot snapshot) { - switch (snapshot.connectionState) { - case ConnectionState.none: - case ConnectionState.waiting: - return const CircularProgressIndicator(); - case ConnectionState.active: - case ConnectionState.done: - if (snapshot.hasError) { - return Text('Error: ${snapshot.error}'); - } else { - return Text( - 'Button tapped ${snapshot.data ?? 0 + _externalCounter} time${(snapshot.data ?? 0 + _externalCounter) == 1 ? '' : 's'}.\n\n' - 'This should persist across restarts.', - ); - } + builder: (BuildContext context) => FutureBuilder( + future: _counter, + builder: (BuildContext context, AsyncSnapshot snapshot) { + switch (snapshot.connectionState) { + case ConnectionState.none: + case ConnectionState.waiting: + return const CircularProgressIndicator(); + case ConnectionState.active: + case ConnectionState.done: + if (snapshot.hasError) { + return Text('Error: ${snapshot.error}'); + } else { + return Text( + 'Button tapped ${snapshot.data ?? 0 + _externalCounter} time${(snapshot.data ?? 0 + _externalCounter) == 1 ? '' : 's'}.\n\n' + 'This should persist across restarts.', + ); } - }, - ), + } + }, + ), ), ), floatingActionButton: FloatingActionButton( diff --git a/packages/shared_preferences/shared_preferences/example/pubspec.yaml b/packages/shared_preferences/shared_preferences/example/pubspec.yaml index 0b8cb9f43ec..24b57336433 100644 --- a/packages/shared_preferences/shared_preferences/example/pubspec.yaml +++ b/packages/shared_preferences/shared_preferences/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the shared_preferences plugin. publish_to: none environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/shared_preferences/shared_preferences/lib/src/shared_preferences_legacy.dart b/packages/shared_preferences/shared_preferences/lib/src/shared_preferences_legacy.dart index 8768b9414f9..e7730a5b04e 100644 --- a/packages/shared_preferences/shared_preferences/lib/src/shared_preferences_legacy.dart +++ b/packages/shared_preferences/shared_preferences/lib/src/shared_preferences_legacy.dart @@ -281,8 +281,8 @@ Either update the implementation to support setPrefix, or do not call setPrefix. } return MapEntry(newKey, value); }); - SharedPreferencesStorePlatform - .instance = InMemorySharedPreferencesStore.withData(newValues); + SharedPreferencesStorePlatform.instance = + InMemorySharedPreferencesStore.withData(newValues); _completer = null; } } diff --git a/packages/shared_preferences/shared_preferences/pubspec.yaml b/packages/shared_preferences/shared_preferences/pubspec.yaml index 37a74d0fc1f..85aeee0c169 100644 --- a/packages/shared_preferences/shared_preferences/pubspec.yaml +++ b/packages/shared_preferences/shared_preferences/pubspec.yaml @@ -6,8 +6,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.5.3 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" flutter: plugin: diff --git a/packages/shared_preferences/shared_preferences/tool/pre_publish.dart b/packages/shared_preferences/shared_preferences/tool/pre_publish.dart index 085aabaf646..fb6ee3d81bf 100644 --- a/packages/shared_preferences/shared_preferences/tool/pre_publish.dart +++ b/packages/shared_preferences/shared_preferences/tool/pre_publish.dart @@ -13,8 +13,9 @@ Future _runCommand({ }) async { stdout.write(message); // The `packages/shared_preferences` directory. - final Directory sharedPreferencesToolParent = - Directory(p.dirname(Platform.script.path)).parent.parent; + final Directory sharedPreferencesToolParent = Directory( + p.dirname(Platform.script.path), + ).parent.parent; final ProcessResult pubGetResult = await Process.run( executable, diff --git a/packages/shared_preferences/shared_preferences_android/CHANGELOG.md b/packages/shared_preferences/shared_preferences_android/CHANGELOG.md index 4e2a0ecde50..c8e50f1c05a 100644 --- a/packages/shared_preferences/shared_preferences_android/CHANGELOG.md +++ b/packages/shared_preferences/shared_preferences_android/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. + ## 2.4.15 * Resolves Gradle 9 deprecations. diff --git a/packages/shared_preferences/shared_preferences_android/example/integration_test/shared_preferences_test.dart b/packages/shared_preferences/shared_preferences_android/example/integration_test/shared_preferences_test.dart index 77a27f8443f..f264f955742 100644 --- a/packages/shared_preferences/shared_preferences_android/example/integration_test/shared_preferences_test.dart +++ b/packages/shared_preferences/shared_preferences_android/example/integration_test/shared_preferences_test.dart @@ -180,8 +180,8 @@ void main() { ), ]); final Map values = - // ignore: deprecated_member_use - await preferences.getAllWithPrefix('prefix.'); + // ignore: deprecated_member_use + await preferences.getAllWithPrefix('prefix.'); expect(values['prefix.String'], allTestValues['prefix.String']); expect(values['prefix.Bool'], allTestValues['prefix.Bool']); expect(values['prefix.Int'], allTestValues['prefix.Int']); @@ -246,8 +246,8 @@ void main() { // ignore: deprecated_member_use await preferences.clearWithPrefix('prefix.'); Map values = - // ignore: deprecated_member_use - await preferences.getAllWithPrefix('prefix.'); + // ignore: deprecated_member_use + await preferences.getAllWithPrefix('prefix.'); expect(values['prefix.String'], null); expect(values['prefix.Bool'], null); expect(values['prefix.Int'], null); @@ -303,8 +303,8 @@ void main() { ), ]); final Map values = - // ignore: deprecated_member_use - await preferences.getAllWithPrefix(''); + // ignore: deprecated_member_use + await preferences.getAllWithPrefix(''); expect(values['String'], allTestValues['String']); expect(values['Bool'], allTestValues['Bool']); expect(values['Int'], allTestValues['Int']); @@ -360,8 +360,8 @@ void main() { // ignore: deprecated_member_use await preferences.clearWithPrefix(''); final Map values = - // ignore: deprecated_member_use - await preferences.getAllWithPrefix(''); + // ignore: deprecated_member_use + await preferences.getAllWithPrefix(''); expect(values['String'], null); expect(values['Bool'], null); expect(values['Int'], null); @@ -694,14 +694,12 @@ void main() { String? fileName, }) { return SharedPreferencesAsyncAndroidOptions( - backend: - useDataStore - ? SharedPreferencesAndroidBackendLibrary.DataStore - : SharedPreferencesAndroidBackendLibrary.SharedPreferences, - originalSharedPreferencesOptions: - fileName == null - ? null - : AndroidSharedPreferencesStoreOptions(fileName: fileName), + backend: useDataStore + ? SharedPreferencesAndroidBackendLibrary.DataStore + : SharedPreferencesAndroidBackendLibrary.SharedPreferences, + originalSharedPreferencesOptions: fileName == null + ? null + : AndroidSharedPreferencesStoreOptions(fileName: fileName), ); } diff --git a/packages/shared_preferences/shared_preferences_android/example/pubspec.yaml b/packages/shared_preferences/shared_preferences_android/example/pubspec.yaml index 6db55ee8b12..8594230b931 100644 --- a/packages/shared_preferences/shared_preferences_android/example/pubspec.yaml +++ b/packages/shared_preferences/shared_preferences_android/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the shared_preferences plugin. publish_to: none environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/shared_preferences/shared_preferences_linux/CHANGELOG.md b/packages/shared_preferences/shared_preferences_linux/CHANGELOG.md index 9093242f28d..92da9403191 100644 --- a/packages/shared_preferences/shared_preferences_linux/CHANGELOG.md +++ b/packages/shared_preferences/shared_preferences_linux/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 2.4.1 diff --git a/packages/shared_preferences/shared_preferences_linux/example/pubspec.yaml b/packages/shared_preferences/shared_preferences_linux/example/pubspec.yaml index 09a5eb558d9..5817c7aa6b1 100644 --- a/packages/shared_preferences/shared_preferences_linux/example/pubspec.yaml +++ b/packages/shared_preferences/shared_preferences_linux/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the shared_preferences_linux plugin. publish_to: none environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/shared_preferences/shared_preferences_linux/pubspec.yaml b/packages/shared_preferences/shared_preferences_linux/pubspec.yaml index 8da7d515d32..282391d1f16 100644 --- a/packages/shared_preferences/shared_preferences_linux/pubspec.yaml +++ b/packages/shared_preferences/shared_preferences_linux/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.4.1 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" flutter: plugin: diff --git a/packages/shared_preferences/shared_preferences_platform_interface/CHANGELOG.md b/packages/shared_preferences/shared_preferences_platform_interface/CHANGELOG.md index 1aea1c08902..2e49ba07bbb 100644 --- a/packages/shared_preferences/shared_preferences_platform_interface/CHANGELOG.md +++ b/packages/shared_preferences/shared_preferences_platform_interface/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 2.4.1 diff --git a/packages/shared_preferences/shared_preferences_platform_interface/pubspec.yaml b/packages/shared_preferences/shared_preferences_platform_interface/pubspec.yaml index 3ea2b4d1aef..e0832298236 100644 --- a/packages/shared_preferences/shared_preferences_platform_interface/pubspec.yaml +++ b/packages/shared_preferences/shared_preferences_platform_interface/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.4.1 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/shared_preferences/shared_preferences_tool/lib/src/shared_preferences_state.dart b/packages/shared_preferences/shared_preferences_tool/lib/src/shared_preferences_state.dart index 9e32211b94b..1b2b00f6cb0 100644 --- a/packages/shared_preferences/shared_preferences_tool/lib/src/shared_preferences_state.dart +++ b/packages/shared_preferences/shared_preferences_tool/lib/src/shared_preferences_state.dart @@ -42,25 +42,26 @@ class SharedPreferencesState { bool editing, bool legacyApi, }) - get copyWith => ({ - Object allKeys = _undefined, - Object? selectedKey = _undefined, - Object editing = _undefined, - Object legacyApi = _undefined, - }) { - return SharedPreferencesState( - allKeys: - allKeys == _undefined + get copyWith => + ({ + Object allKeys = _undefined, + Object? selectedKey = _undefined, + Object editing = _undefined, + Object legacyApi = _undefined, + }) { + return SharedPreferencesState( + allKeys: allKeys == _undefined ? this.allKeys : allKeys as AsyncState>, - selectedKey: - selectedKey == _undefined + selectedKey: selectedKey == _undefined ? this.selectedKey : selectedKey as SelectedSharedPreferencesKey?, - editing: editing == _undefined ? this.editing : editing as bool, - legacyApi: legacyApi == _undefined ? this.legacyApi : legacyApi as bool, - ); - }; + editing: editing == _undefined ? this.editing : editing as bool, + legacyApi: legacyApi == _undefined + ? this.legacyApi + : legacyApi as bool, + ); + }; @override bool operator ==(Object other) { diff --git a/packages/shared_preferences/shared_preferences_tool/lib/src/ui/data_panel.dart b/packages/shared_preferences/shared_preferences_tool/lib/src/ui/data_panel.dart index 97ca43266a6..24f45dfb0da 100644 --- a/packages/shared_preferences/shared_preferences_tool/lib/src/ui/data_panel.dart +++ b/packages/shared_preferences/shared_preferences_tool/lib/src/ui/data_panel.dart @@ -120,19 +120,18 @@ class _Header extends StatelessWidget { context.sharedPreferencesStateNotifier; showDialog( context: context, - builder: - (BuildContext context) => _ConfirmRemoveDialog( - selectedKey: selectedKey, - notifier: notifier, - ), + builder: (BuildContext context) => _ConfirmRemoveDialog( + selectedKey: selectedKey, + notifier: notifier, + ), ); }, label: 'Remove', ), const SizedBox(width: denseRowSpacing), DevToolsButton( - onPressed: - () => context.sharedPreferencesStateNotifier.startEditing(), + onPressed: () => + context.sharedPreferencesStateNotifier.startEditing(), label: 'Edit', ), ], @@ -345,7 +344,9 @@ class _AddListElement extends StatelessWidget { @override Widget build(BuildContext context) { - return Center(child: DevToolsButton(icon: Icons.add, onPressed: onPressed)); + return Center( + child: DevToolsButton(icon: Icons.add, onPressed: onPressed), + ); } } diff --git a/packages/shared_preferences/shared_preferences_tool/lib/src/ui/keys_panel.dart b/packages/shared_preferences/shared_preferences_tool/lib/src/ui/keys_panel.dart index af667209263..361a6f89758 100644 --- a/packages/shared_preferences/shared_preferences_tool/lib/src/ui/keys_panel.dart +++ b/packages/shared_preferences/shared_preferences_tool/lib/src/ui/keys_panel.dart @@ -227,8 +227,9 @@ class _KeyItem extends StatelessWidget { SharedPreferencesStateProvider.selectedKeyOf(context); final bool isSelected = selectedKey?.key == keyName; final ColorScheme colorScheme = Theme.of(context).colorScheme; - final Color? backgroundColor = - isSelected ? colorScheme.selectedRowBackgroundColor : null; + final Color? backgroundColor = isSelected + ? colorScheme.selectedRowBackgroundColor + : null; return InkWell( onTap: () { diff --git a/packages/shared_preferences/shared_preferences_tool/pubspec.yaml b/packages/shared_preferences/shared_preferences_tool/pubspec.yaml index 141f70870c7..bafd381ac21 100644 --- a/packages/shared_preferences/shared_preferences_tool/pubspec.yaml +++ b/packages/shared_preferences/shared_preferences_tool/pubspec.yaml @@ -5,7 +5,7 @@ publish_to: 'none' version: 1.0.1 environment: - sdk: ^3.7.0 + sdk: ^3.8.0 dependencies: devtools_app_shared: ^0.3.0 diff --git a/packages/shared_preferences/shared_preferences_tool/test/src/shared_preferences_state_notifier_test.mocks.dart b/packages/shared_preferences/shared_preferences_tool/test/src/shared_preferences_state_notifier_test.mocks.dart index 7bf8aca636d..89fb66be1f0 100644 --- a/packages/shared_preferences/shared_preferences_tool/test/src/shared_preferences_state_notifier_test.mocks.dart +++ b/packages/shared_preferences/shared_preferences_tool/test/src/shared_preferences_state_notifier_test.mocks.dart @@ -41,12 +41,14 @@ class MockSharedPreferencesToolEval extends _i1.Mock fetchAllKeys() => (super.noSuchMethod( Invocation.method(#fetchAllKeys, []), - returnValue: _i2.Future< - ({List asyncKeys, List legacyKeys}) - >.value((asyncKeys: [], legacyKeys: [])), - returnValueForMissingStub: _i2.Future< - ({List asyncKeys, List legacyKeys}) - >.value((asyncKeys: [], legacyKeys: [])), + returnValue: + _i2.Future< + ({List asyncKeys, List legacyKeys}) + >.value((asyncKeys: [], legacyKeys: [])), + returnValueForMissingStub: + _i2.Future< + ({List asyncKeys, List legacyKeys}) + >.value((asyncKeys: [], legacyKeys: [])), ) as _i2.Future<({List asyncKeys, List legacyKeys})>); diff --git a/packages/shared_preferences/shared_preferences_tool/test/src/ui/data_panel_test.dart b/packages/shared_preferences/shared_preferences_tool/test/src/ui/data_panel_test.dart index 861cde351f8..8cda3bceddb 100644 --- a/packages/shared_preferences/shared_preferences_tool/test/src/ui/data_panel_test.dart +++ b/packages/shared_preferences/shared_preferences_tool/test/src/ui/data_panel_test.dart @@ -50,13 +50,9 @@ void main() { SharedPreferencesState( allKeys: const AsyncState>.data([selectedKey]), editing: editing, - selectedKey: - state == null - ? null - : SelectedSharedPreferencesKey( - key: selectedKey, - value: state, - ), + selectedKey: state == null + ? null + : SelectedSharedPreferencesKey(key: selectedKey, value: state), ), ); } diff --git a/packages/shared_preferences/shared_preferences_tool/test/src/ui/keys_panel_test.dart b/packages/shared_preferences/shared_preferences_tool/test/src/ui/keys_panel_test.dart index 09000243bb2..a3f6365fa8d 100644 --- a/packages/shared_preferences/shared_preferences_tool/test/src/ui/keys_panel_test.dart +++ b/packages/shared_preferences/shared_preferences_tool/test/src/ui/keys_panel_test.dart @@ -109,10 +109,9 @@ void main() { final ColorScheme colorScheme = Theme.of(selectedKeyElement).colorScheme; Color? bgColorFor(String key) { - final Container? container = - tester - .element(find.text(key)) - .findAncestorWidgetOfExactType(); + final Container? container = tester + .element(find.text(key)) + .findAncestorWidgetOfExactType(); return container?.color; } diff --git a/packages/shared_preferences/shared_preferences_web/CHANGELOG.md b/packages/shared_preferences/shared_preferences_web/CHANGELOG.md index 13fe74f4fdc..6e39a9f56cf 100644 --- a/packages/shared_preferences/shared_preferences_web/CHANGELOG.md +++ b/packages/shared_preferences/shared_preferences_web/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 2.4.3 diff --git a/packages/shared_preferences/shared_preferences_web/example/integration_test/shared_preferences_web_test.dart b/packages/shared_preferences/shared_preferences_web/example/integration_test/shared_preferences_web_test.dart index ed0d7a83aeb..3f90791c9fd 100644 --- a/packages/shared_preferences/shared_preferences_web/example/integration_test/shared_preferences_web_test.dart +++ b/packages/shared_preferences/shared_preferences_web/example/integration_test/shared_preferences_web_test.dart @@ -171,15 +171,15 @@ void main() { const String key = 'flutter.String'; await preferences.remove(key); final Map values = - // ignore: deprecated_member_use - await preferences.getAllWithPrefix(''); + // ignore: deprecated_member_use + await preferences.getAllWithPrefix(''); expect(values[key], isNull); }); testWidgets('get all with prefix', (WidgetTester _) async { final Map values = - // ignore: deprecated_member_use - await preferences.getAllWithPrefix('prefix.'); + // ignore: deprecated_member_use + await preferences.getAllWithPrefix('prefix.'); expect(values['prefix.String'], allTestValues['prefix.String']); expect(values['prefix.Bool'], allTestValues['prefix.Bool']); expect(values['prefix.Int'], allTestValues['prefix.Int']); @@ -189,8 +189,8 @@ void main() { testWidgets('getAllWithNoPrefix', (WidgetTester _) async { final Map values = - // ignore: deprecated_member_use - await preferences.getAllWithPrefix(''); + // ignore: deprecated_member_use + await preferences.getAllWithPrefix(''); expect(values['String'], allTestValues['String']); expect(values['Bool'], allTestValues['Bool']); expect(values['Int'], allTestValues['Int']); @@ -210,8 +210,8 @@ void main() { // ignore: deprecated_member_use await preferences.clearWithPrefix('prefix.'); Map values = - // ignore: deprecated_member_use - await preferences.getAllWithPrefix('prefix.'); + // ignore: deprecated_member_use + await preferences.getAllWithPrefix('prefix.'); expect(values['prefix.String'], null); expect(values['prefix.Bool'], null); expect(values['prefix.Int'], null); @@ -233,8 +233,8 @@ void main() { // ignore: deprecated_member_use await preferences.clearWithPrefix(''); final Map values = - // ignore: deprecated_member_use - await preferences.getAllWithPrefix(''); + // ignore: deprecated_member_use + await preferences.getAllWithPrefix(''); expect(values['String'], null); expect(values['Bool'], null); expect(values['Int'], null); diff --git a/packages/shared_preferences/shared_preferences_web/example/pubspec.yaml b/packages/shared_preferences/shared_preferences_web/example/pubspec.yaml index 4b435959694..e44f580a0ce 100644 --- a/packages/shared_preferences/shared_preferences_web/example/pubspec.yaml +++ b/packages/shared_preferences/shared_preferences_web/example/pubspec.yaml @@ -2,8 +2,8 @@ name: shared_preferences_web_integration_tests publish_to: none environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/shared_preferences/shared_preferences_web/pubspec.yaml b/packages/shared_preferences/shared_preferences_web/pubspec.yaml index 381aadd6cc8..e26903bb93a 100644 --- a/packages/shared_preferences/shared_preferences_web/pubspec.yaml +++ b/packages/shared_preferences/shared_preferences_web/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.4.3 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" flutter: plugin: diff --git a/packages/shared_preferences/shared_preferences_windows/CHANGELOG.md b/packages/shared_preferences/shared_preferences_windows/CHANGELOG.md index c9f928ec7a0..643c4b915a7 100644 --- a/packages/shared_preferences/shared_preferences_windows/CHANGELOG.md +++ b/packages/shared_preferences/shared_preferences_windows/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 2.4.1 diff --git a/packages/shared_preferences/shared_preferences_windows/example/pubspec.yaml b/packages/shared_preferences/shared_preferences_windows/example/pubspec.yaml index 0940a9d9f74..7a20b1d7ad1 100644 --- a/packages/shared_preferences/shared_preferences_windows/example/pubspec.yaml +++ b/packages/shared_preferences/shared_preferences_windows/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the shared_preferences_windows plugin. publish_to: none environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/shared_preferences/shared_preferences_windows/pubspec.yaml b/packages/shared_preferences/shared_preferences_windows/pubspec.yaml index 7a6ee676c34..df1cc8d2ceb 100644 --- a/packages/shared_preferences/shared_preferences_windows/pubspec.yaml +++ b/packages/shared_preferences/shared_preferences_windows/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.4.1 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" flutter: plugin: diff --git a/packages/standard_message_codec/CHANGELOG.md b/packages/standard_message_codec/CHANGELOG.md index 6196c6ad631..254718162ef 100644 --- a/packages/standard_message_codec/CHANGELOG.md +++ b/packages/standard_message_codec/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 0.0.1+4 diff --git a/packages/standard_message_codec/example/pubspec.yaml b/packages/standard_message_codec/example/pubspec.yaml index e3faa9400ab..ef638a0e720 100644 --- a/packages/standard_message_codec/example/pubspec.yaml +++ b/packages/standard_message_codec/example/pubspec.yaml @@ -4,7 +4,7 @@ version: 0.0.1 publish_to: none environment: - sdk: ^3.7.0 + sdk: ^3.8.0 dependencies: standard_message_codec: diff --git a/packages/standard_message_codec/pubspec.yaml b/packages/standard_message_codec/pubspec.yaml index ddfb1a8c94f..a98decf5d25 100644 --- a/packages/standard_message_codec/pubspec.yaml +++ b/packages/standard_message_codec/pubspec.yaml @@ -5,7 +5,7 @@ repository: https://github.com/flutter/packages/tree/main/packages/standard_mess issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3Astandard_message_codec environment: - sdk: ^3.7.0 + sdk: ^3.8.0 dev_dependencies: test: ^1.16.0 diff --git a/packages/two_dimensional_scrollables/CHANGELOG.md b/packages/two_dimensional_scrollables/CHANGELOG.md index 310ef7b53ff..f998911301e 100644 --- a/packages/two_dimensional_scrollables/CHANGELOG.md +++ b/packages/two_dimensional_scrollables/CHANGELOG.md @@ -1,7 +1,7 @@ ## NEXT * Updates examples to use the new RadioGroup API instead of deprecated Radio parameters. -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 0.3.7 diff --git a/packages/two_dimensional_scrollables/example/lib/table_view/merged_table.dart b/packages/two_dimensional_scrollables/example/lib/table_view/merged_table.dart index dc694c05c69..4c25dcb8d3a 100644 --- a/packages/two_dimensional_scrollables/example/lib/table_view/merged_table.dart +++ b/packages/two_dimensional_scrollables/example/lib/table_view/merged_table.dart @@ -101,8 +101,8 @@ class _MergedTableExampleState extends State { final ({String name, Color color}) cell = _getColorForVicinity(vicinity); final Color textColor = ThemeData.estimateBrightnessForColor(cell.color) == Brightness.light - ? Colors.black - : Colors.white; + ? Colors.black + : Colors.white; final TextStyle style = TextStyle( color: textColor, fontSize: 18.0, @@ -121,14 +121,13 @@ class _MergedTableExampleState extends State { TableSpan _buildColumnSpan(int index) { return TableSpan( extent: FixedTableSpanExtent(index == 0 ? 220 : 180), - foregroundDecoration: - index == 0 - ? const TableSpanDecoration( - border: TableSpanBorder( - trailing: BorderSide(width: 5, color: Colors.white), - ), - ) - : null, + foregroundDecoration: index == 0 + ? const TableSpanDecoration( + border: TableSpanBorder( + trailing: BorderSide(width: 5, color: Colors.white), + ), + ) + : null, ); } diff --git a/packages/two_dimensional_scrollables/example/lib/table_view/simple_table.dart b/packages/two_dimensional_scrollables/example/lib/table_view/simple_table.dart index 1acf02c0d73..0ea73b423ad 100644 --- a/packages/two_dimensional_scrollables/example/lib/table_view/simple_table.dart +++ b/packages/two_dimensional_scrollables/example/lib/table_view/simple_table.dart @@ -37,21 +37,9 @@ class _TableExampleState extends State { return Scaffold( body: Padding( padding: const EdgeInsets.symmetric(horizontal: 50.0), - child: - _selectionMode == _TableSelection.multiCell - ? SelectionArea( - child: TableView.builder( - verticalDetails: ScrollableDetails.vertical( - controller: _verticalController, - ), - cellBuilder: _buildCell, - columnCount: 20, - columnBuilder: _buildColumnSpan, - rowCount: _rowCount, - rowBuilder: _buildRowSpan, - ), - ) - : TableView.builder( + child: _selectionMode == _TableSelection.multiCell + ? SelectionArea( + child: TableView.builder( verticalDetails: ScrollableDetails.vertical( controller: _verticalController, ), @@ -61,6 +49,17 @@ class _TableExampleState extends State { rowCount: _rowCount, rowBuilder: _buildRowSpan, ), + ) + : TableView.builder( + verticalDetails: ScrollableDetails.vertical( + controller: _verticalController, + ), + cellBuilder: _buildCell, + columnCount: 20, + columnBuilder: _buildColumnSpan, + rowCount: _rowCount, + rowBuilder: _buildRowSpan, + ), ), persistentFooterButtons: [ OverflowBar( diff --git a/packages/two_dimensional_scrollables/example/lib/tree_view/custom_tree.dart b/packages/two_dimensional_scrollables/example/lib/tree_view/custom_tree.dart index e477f603a9d..bb3cebbbf0d 100644 --- a/packages/two_dimensional_scrollables/example/lib/tree_view/custom_tree.dart +++ b/packages/two_dimensional_scrollables/example/lib/tree_view/custom_tree.dart @@ -120,10 +120,9 @@ class CustomTreeExampleState extends State { SizedBox(width: 10.0 * node.depth! + 8.0), DecoratedBox( decoration: BoxDecoration( - border: - node.parent != null - ? Border(left: border, bottom: border) - : null, + border: node.parent != null + ? Border(left: border, bottom: border) + : null, ), child: const SizedBox(height: 50.0, width: 20.0), ), @@ -148,12 +147,10 @@ class CustomTreeExampleState extends State { TreeViewNode node, ) { return { - TapGestureRecognizer: GestureRecognizerFactoryWithHandlers< - TapGestureRecognizer - >( - () => TapGestureRecognizer(), - (TapGestureRecognizer t) => - t.onTap = () { + TapGestureRecognizer: + GestureRecognizerFactoryWithHandlers( + () => TapGestureRecognizer(), + (TapGestureRecognizer t) => t.onTap = () { setState(() { // Toggling the node here instead means any tap on the row can // toggle parent nodes opened and closed. @@ -161,7 +158,7 @@ class CustomTreeExampleState extends State { _selectedNode = node; }); }, - ), + ), }; } diff --git a/packages/two_dimensional_scrollables/example/lib/tree_view/simple_tree.dart b/packages/two_dimensional_scrollables/example/lib/tree_view/simple_tree.dart index d56f9b88eb7..cdcbf15a6aa 100644 --- a/packages/two_dimensional_scrollables/example/lib/tree_view/simple_tree.dart +++ b/packages/two_dimensional_scrollables/example/lib/tree_view/simple_tree.dart @@ -71,12 +71,11 @@ class TreeExampleState extends State { TapGestureRecognizer: GestureRecognizerFactoryWithHandlers( () => TapGestureRecognizer(), - (TapGestureRecognizer t) => - t.onTap = () { - setState(() { - _selectedNode = node; - }); - }, + (TapGestureRecognizer t) => t.onTap = () { + setState(() { + _selectedNode = node; + }); + }, ), }; } diff --git a/packages/two_dimensional_scrollables/example/pubspec.yaml b/packages/two_dimensional_scrollables/example/pubspec.yaml index 5801de5d0b3..61ccabdc15a 100644 --- a/packages/two_dimensional_scrollables/example/pubspec.yaml +++ b/packages/two_dimensional_scrollables/example/pubspec.yaml @@ -6,8 +6,8 @@ publish_to: 'none' version: 2.0.0 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/two_dimensional_scrollables/lib/src/common/span.dart b/packages/two_dimensional_scrollables/lib/src/common/span.dart index 395727235b0..6a072091d2f 100644 --- a/packages/two_dimensional_scrollables/lib/src/common/span.dart +++ b/packages/two_dimensional_scrollables/lib/src/common/span.dart @@ -383,10 +383,9 @@ class SpanDecoration { /// cells. void paint(SpanDecorationPaintDetails details) { if (color != null) { - final Paint paint = - Paint() - ..color = color! - ..isAntiAlias = borderRadius != null; + final Paint paint = Paint() + ..color = color! + ..isAntiAlias = borderRadius != null; if (borderRadius == null || borderRadius == BorderRadius.zero) { details.canvas.drawRect(details.rect, paint); } else { diff --git a/packages/two_dimensional_scrollables/lib/src/table_view/table.dart b/packages/two_dimensional_scrollables/lib/src/table_view/table.dart index 43b5725fa14..e8f4f4b1cb2 100644 --- a/packages/two_dimensional_scrollables/lib/src/table_view/table.dart +++ b/packages/two_dimensional_scrollables/lib/src/table_view/table.dart @@ -397,14 +397,12 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { int? get _lastPinnedColumn => delegate.pinnedColumnCount > 0 ? delegate.pinnedColumnCount - 1 : null; - double get _pinnedRowsExtent => - _lastPinnedRow != null - ? _rowMetrics[_lastPinnedRow]!.trailingOffset - : 0.0; - double get _pinnedColumnsExtent => - _lastPinnedColumn != null - ? _columnMetrics[_lastPinnedColumn]!.trailingOffset - : 0.0; + double get _pinnedRowsExtent => _lastPinnedRow != null + ? _rowMetrics[_lastPinnedRow]!.trailingOffset + : 0.0; + double get _pinnedColumnsExtent => _lastPinnedColumn != null + ? _columnMetrics[_lastPinnedColumn]!.trailingOffset + : 0.0; @override TableViewParentData parentDataOf(RenderBox child) => @@ -497,8 +495,9 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { } // If we are computing up to a specific index, we are getting info for a // merged cell, do not change the visible cells. - _firstNonPinnedColumn = - toColumnIndex == null ? null : _firstNonPinnedColumn; + _firstNonPinnedColumn = toColumnIndex == null + ? null + : _firstNonPinnedColumn; _lastNonPinnedColumn = toColumnIndex == null ? null : _lastNonPinnedColumn; int column = appendColumns ? _columnMetrics.length : 0; @@ -522,8 +521,9 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { while (!reachedColumnEnd()) { final bool isPinned = column < delegate.pinnedColumnCount; - final double leadingOffset = - isPinned ? startOfPinnedColumn : startOfRegularColumn; + final double leadingOffset = isPinned + ? startOfPinnedColumn + : startOfRegularColumn; _Span? span = _columnMetrics.remove(column); final TableSpan? configuration = span?.configuration ?? delegate.buildColumn(column); @@ -623,8 +623,9 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { while (!reachedRowEnd()) { final bool isPinned = row < delegate.pinnedRowCount; - final double leadingOffset = - isPinned ? startOfPinnedRow : startOfRegularRow; + final double leadingOffset = isPinned + ? startOfPinnedRow + : startOfRegularRow; _Span? span = _rowMetrics.remove(row); final TableSpan? configuration = span?.configuration ?? delegate.buildRow(row); @@ -842,18 +843,16 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { return; } - final double? offsetIntoColumn = - _firstNonPinnedColumn != null - ? horizontalOffset.pixels - - _columnMetrics[_firstNonPinnedColumn]!.leadingOffset - - _pinnedColumnsExtent - : null; - final double? offsetIntoRow = - _firstNonPinnedRow != null - ? verticalOffset.pixels - - _rowMetrics[_firstNonPinnedRow]!.leadingOffset - - _pinnedRowsExtent - : null; + final double? offsetIntoColumn = _firstNonPinnedColumn != null + ? horizontalOffset.pixels - + _columnMetrics[_firstNonPinnedColumn]!.leadingOffset - + _pinnedColumnsExtent + : null; + final double? offsetIntoRow = _firstNonPinnedRow != null + ? verticalOffset.pixels - + _rowMetrics[_firstNonPinnedRow]!.leadingOffset - + _pinnedRowsExtent + : null; if (_lastPinnedRow != null && _lastPinnedColumn != null) { // Layout cells that are contained in both pinned rows and columns _layoutCells( @@ -963,10 +962,9 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { columnOffset += colSpan.configuration.padding.leading; final TableVicinity vicinity = TableVicinity(column: column, row: row); - final RenderBox? cell = - _mergedVicinities.keys.contains(vicinity) - ? null - : buildOrObtainChildFor(vicinity); + final RenderBox? cell = _mergedVicinities.keys.contains(vicinity) + ? null + : buildOrObtainChildFor(vicinity); if (cell != null) { final TableViewParentData cellParentData = parentDataOf(cell); @@ -975,10 +973,9 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { if (cellParentData.rowMergeStart != null || cellParentData.columnMergeStart != null) { final int firstRow = cellParentData.rowMergeStart ?? row; - final int lastRow = - cellParentData.rowMergeStart == null - ? row - : firstRow + cellParentData.rowMergeSpan! - 1; + final int lastRow = cellParentData.rowMergeStart == null + ? row + : firstRow + cellParentData.rowMergeSpan! - 1; assert( _debugCheckMergeBounds( spanOrientation: 'Row', @@ -992,10 +989,9 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { ); final int firstColumn = cellParentData.columnMergeStart ?? column; - final int lastColumn = - cellParentData.columnMergeStart == null - ? column - : firstColumn + cellParentData.columnMergeSpan! - 1; + final int lastColumn = cellParentData.columnMergeStart == null + ? column + : firstColumn + cellParentData.columnMergeSpan! - 1; assert( _debugCheckMergeBounds( spanOrientation: 'Column', @@ -1341,14 +1337,12 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { if (_mergedColumns.isEmpty || !_mergedColumns.contains(column)) { // One decoration across the whole column. decorationCells.add(( - leading: - getChildFor( - TableVicinity(column: column, row: leadingVicinity.row), - )!, - trailing: - getChildFor( - TableVicinity(column: column, row: trailingVicinity.row), - )!, + leading: getChildFor( + TableVicinity(column: column, row: leadingVicinity.row), + )!, + trailing: getChildFor( + TableVicinity(column: column, row: trailingVicinity.row), + )!, )); } else { // Walk through the rows to separate merged cells for decorating. A @@ -1413,11 +1407,11 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { }) { final ({double leading, double trailing}) offsetCorrection = axisDirectionIsReversed(verticalAxisDirection) - ? ( - leading: leadingCell.size.height, - trailing: trailingCell.size.height, - ) - : (leading: 0.0, trailing: 0.0); + ? ( + leading: leadingCell.size.height, + trailing: trailingCell.size.height, + ) + : (leading: 0.0, trailing: 0.0); return Rect.fromPoints( parentDataOf(leadingCell).paintOffset! + offset - @@ -1482,14 +1476,12 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { if (_mergedRows.isEmpty || !_mergedRows.contains(row)) { // One decoration across the whole row. decorationCells.add(( - leading: - getChildFor( - TableVicinity(column: leadingVicinity.column, row: row), - )!, // leading - trailing: - getChildFor( - TableVicinity(column: trailingVicinity.column, row: row), - )!, // trailing + leading: getChildFor( + TableVicinity(column: leadingVicinity.column, row: row), + )!, // leading + trailing: getChildFor( + TableVicinity(column: trailingVicinity.column, row: row), + )!, // trailing )); } else { // Walk through the columns to separate merged cells for decorating. A @@ -1554,11 +1546,11 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { }) { final ({double leading, double trailing}) offsetCorrection = axisDirectionIsReversed(horizontalAxisDirection) - ? ( - leading: leadingCell.size.width, - trailing: trailingCell.size.width, - ) - : (leading: 0.0, trailing: 0.0); + ? ( + leading: leadingCell.size.width, + trailing: trailingCell.size.width, + ) + : (leading: 0.0, trailing: 0.0); return Rect.fromPoints( parentDataOf(leadingCell).paintOffset! + offset - diff --git a/packages/two_dimensional_scrollables/lib/src/table_view/table_delegate.dart b/packages/two_dimensional_scrollables/lib/src/table_view/table_delegate.dart index 7c22b4956c7..152006eae3f 100644 --- a/packages/two_dimensional_scrollables/lib/src/table_view/table_delegate.dart +++ b/packages/two_dimensional_scrollables/lib/src/table_view/table_delegate.dart @@ -159,9 +159,8 @@ class TableCellBuilderDelegate extends TwoDimensionalChildBuilderDelegate _pinnedColumnCount = pinnedColumnCount, _pinnedRowCount = pinnedRowCount, super( - builder: - (BuildContext context, ChildVicinity vicinity) => - cellBuilder(context, vicinity as TableVicinity), + builder: (BuildContext context, ChildVicinity vicinity) => + cellBuilder(context, vicinity as TableVicinity), maxXIndex: columnCount == null ? columnCount : columnCount - 1, maxYIndex: rowCount == null ? rowCount : rowCount - 1, // repaintBoundaries handled by TableViewCell diff --git a/packages/two_dimensional_scrollables/lib/src/tree_view/render_tree.dart b/packages/two_dimensional_scrollables/lib/src/tree_view/render_tree.dart index ef643532d1d..94a1acbd164 100644 --- a/packages/two_dimensional_scrollables/lib/src/tree_view/render_tree.dart +++ b/packages/two_dimensional_scrollables/lib/src/tree_view/render_tree.dart @@ -210,15 +210,11 @@ class RenderTreeViewport extends RenderTwoDimensionalViewport { while (currentIndex <= lastIndex && currentPosition < _targetRowPixel) { _Span? span = _rowMetrics.remove(currentIndex); assert(needsDelegateRebuild || span != null); - final TreeRow configuration = - needsDelegateRebuild - ? delegate.buildRow( - TreeVicinity( - depth: _rowDepths[currentIndex]!, - row: currentIndex, - ), - ) - : span!.configuration; + final TreeRow configuration = needsDelegateRebuild + ? delegate.buildRow( + TreeVicinity(depth: _rowDepths[currentIndex]!, row: currentIndex), + ) + : span!.configuration; span ??= _Span(); final double extent = configuration.extent.calculateExtent( TreeRowExtentDelegate( @@ -250,12 +246,9 @@ class RenderTreeViewport extends RenderTwoDimensionalViewport { final double leadingOffset = startOfRow; _Span? span = _rowMetrics.remove(row); assert(needsDelegateRebuild || span != null); - final TreeRow configuration = - needsDelegateRebuild - ? delegate.buildRow( - TreeVicinity(depth: _rowDepths[row]!, row: row), - ) - : span!.configuration; + final TreeRow configuration = needsDelegateRebuild + ? delegate.buildRow(TreeVicinity(depth: _rowDepths[row]!, row: row)) + : span!.configuration; span ??= _Span(); final double extent = configuration.extent.calculateExtent( TreeRowExtentDelegate( @@ -450,8 +443,8 @@ class RenderTreeViewport extends RenderTwoDimensionalViewport { // We are animating. // Separate animating segments to clip for any overlap. int leadingIndex = _firstRow!; - final List animationIndices = - _animationLeadingIndices.keys.toList()..sort(); + final List animationIndices = _animationLeadingIndices.keys.toList() + ..sort(); final List<_PaintSegment> paintSegments = <_PaintSegment>[]; while (animationIndices.isNotEmpty) { final int trailingIndex = animationIndices.removeAt(0); @@ -548,10 +541,9 @@ class RenderTreeViewport extends RenderTwoDimensionalViewport { final TreeRow configuration = rowSpan.configuration; if (configuration.backgroundDecoration != null || configuration.foregroundDecoration != null) { - final RenderBox child = - getChildFor( - TreeVicinity(depth: _rowDepths[currentRow]!, row: currentRow), - )!; + final RenderBox child = getChildFor( + TreeVicinity(depth: _rowDepths[currentRow]!, row: currentRow), + )!; Rect getRowRect(bool consumePadding) { final TwoDimensionalViewportParentData parentData = parentDataOf( @@ -597,8 +589,9 @@ class RenderTreeViewport extends RenderTwoDimensionalViewport { }); // Child nodes. for (int row = leadingRow; row <= trailingRow; row++) { - final RenderBox child = - getChildFor(TreeVicinity(depth: _rowDepths[row]!, row: row))!; + final RenderBox child = getChildFor( + TreeVicinity(depth: _rowDepths[row]!, row: row), + )!; final TwoDimensionalViewportParentData rowParentData = parentDataOf( child, ); diff --git a/packages/two_dimensional_scrollables/lib/src/tree_view/tree.dart b/packages/two_dimensional_scrollables/lib/src/tree_view/tree.dart index a6d6a9cd48d..b026767d6c0 100644 --- a/packages/two_dimensional_scrollables/lib/src/tree_view/tree.dart +++ b/packages/two_dimensional_scrollables/lib/src/tree_view/tree.dart @@ -219,8 +219,8 @@ class TreeViewController { /// add a [Builder] widget, which provides a new scope with a /// [BuildContext] that is "under" the [TreeView]. static TreeViewController of(BuildContext context) { - final _TreeViewState? result = - context.findAncestorStateOfType<_TreeViewState>(); + final _TreeViewState? result = context + .findAncestorStateOfType<_TreeViewState>(); if (result != null) { return result.controller; } @@ -579,17 +579,16 @@ class TreeView extends StatefulWidget { node: node, child: SizedBox.square( dimension: 30.0, - child: - node.children.isNotEmpty - ? AnimatedRotation( - key: ValueKey(index), - turns: node.isExpanded ? 0.25 : 0.0, - duration: animationDuration, - curve: animationCurve, - // Renders a unicode right-facing arrow. > - child: const Icon(IconData(0x25BA), size: 14), - ) - : null, + child: node.children.isNotEmpty + ? AnimatedRotation( + key: ValueKey(index), + turns: node.isExpanded ? 0.25 : 0.0, + duration: animationDuration, + curve: animationCurve, + // Renders a unicode right-facing arrow. > + child: const Icon(IconData(0x25BA), size: 14), + ) + : null, ), ), // Spacer @@ -606,12 +605,11 @@ class TreeView extends StatefulWidget { } // Used in TreeViewState for code simplicity. -typedef _AnimationRecord = - ({ - AnimationController controller, - CurvedAnimation animation, - UniqueKey key, - }); +typedef _AnimationRecord = ({ + AnimationController controller, + CurvedAnimation animation, + UniqueKey key, +}); class _TreeViewState extends State> with TickerProviderStateMixin, TreeViewStateMixin { diff --git a/packages/two_dimensional_scrollables/pubspec.yaml b/packages/two_dimensional_scrollables/pubspec.yaml index 2e83c725bc7..4050ce61a82 100644 --- a/packages/two_dimensional_scrollables/pubspec.yaml +++ b/packages/two_dimensional_scrollables/pubspec.yaml @@ -5,8 +5,8 @@ repository: https://github.com/flutter/packages/tree/main/packages/two_dimension issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+two_dimensional_scrollables%22+ environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/two_dimensional_scrollables/test/table_view/table_delegate_test.dart b/packages/two_dimensional_scrollables/test/table_view/table_delegate_test.dart index 55f7a1cc0d2..69a0ef23004 100644 --- a/packages/two_dimensional_scrollables/test/table_view/table_delegate_test.dart +++ b/packages/two_dimensional_scrollables/test/table_view/table_delegate_test.dart @@ -384,8 +384,8 @@ void main() { [cell, cell, cell], [cell, cell, cell], ], - columnBuilder: - (int index) => const TableSpan(extent: FixedTableSpanExtent(150)), + columnBuilder: (int index) => + const TableSpan(extent: FixedTableSpanExtent(150)), rowBuilder: spanBuilder, ); expect(delegate.shouldRebuild(oldDelegate), isTrue); @@ -398,8 +398,8 @@ void main() { [cell, cell, cell], [cell, cell, cell], ], - columnBuilder: - (int index) => const TableSpan(extent: FixedTableSpanExtent(150)), + columnBuilder: (int index) => + const TableSpan(extent: FixedTableSpanExtent(150)), rowBuilder: spanBuilder, ); expect(delegate.shouldRebuild(oldDelegate), isTrue); @@ -412,10 +412,10 @@ void main() { [cell, cell, cell], [cell, cell, cell], ], - columnBuilder: - (int index) => const TableSpan(extent: FixedTableSpanExtent(150)), - rowBuilder: - (int index) => const TableSpan(extent: RemainingTableSpanExtent()), + columnBuilder: (int index) => + const TableSpan(extent: FixedTableSpanExtent(150)), + rowBuilder: (int index) => + const TableSpan(extent: RemainingTableSpanExtent()), ); expect(delegate.shouldRebuild(oldDelegate), isTrue); @@ -427,10 +427,10 @@ void main() { [cell, cell, cell], [cell, cell, cell], ], - columnBuilder: - (int index) => const TableSpan(extent: FixedTableSpanExtent(150)), - rowBuilder: - (int index) => const TableSpan(extent: RemainingTableSpanExtent()), + columnBuilder: (int index) => + const TableSpan(extent: FixedTableSpanExtent(150)), + rowBuilder: (int index) => + const TableSpan(extent: RemainingTableSpanExtent()), pinnedRowCount: 2, ); expect(delegate.shouldRebuild(oldDelegate), isTrue); @@ -443,10 +443,10 @@ void main() { [cell, cell, cell], [cell, cell, cell], ], - columnBuilder: - (int index) => const TableSpan(extent: FixedTableSpanExtent(150)), - rowBuilder: - (int index) => const TableSpan(extent: RemainingTableSpanExtent()), + columnBuilder: (int index) => + const TableSpan(extent: FixedTableSpanExtent(150)), + rowBuilder: (int index) => + const TableSpan(extent: RemainingTableSpanExtent()), pinnedColumnCount: 2, pinnedRowCount: 2, ); @@ -463,10 +463,10 @@ void main() { [cell, cell, cell], [cell, cell, cell], ], - columnBuilder: - (int index) => const TableSpan(extent: FixedTableSpanExtent(150)), - rowBuilder: - (int index) => const TableSpan(extent: RemainingTableSpanExtent()), + columnBuilder: (int index) => + const TableSpan(extent: FixedTableSpanExtent(150)), + rowBuilder: (int index) => + const TableSpan(extent: RemainingTableSpanExtent()), pinnedColumnCount: 2, pinnedRowCount: 2, ); diff --git a/packages/two_dimensional_scrollables/test/table_view/table_span_test.dart b/packages/two_dimensional_scrollables/test/table_view/table_span_test.dart index a0ad4d13c03..d0a8010bf04 100644 --- a/packages/two_dimensional_scrollables/test/table_view/table_span_test.dart +++ b/packages/two_dimensional_scrollables/test/table_view/table_span_test.dart @@ -925,8 +925,9 @@ void main() { } return TableSpan( extent: const FixedTableSpanExtent(100.0), - backgroundDecoration: - color == null ? null : TableSpanDecoration(color: color), + backgroundDecoration: color == null + ? null + : TableSpanDecoration(color: color), ); }, ); @@ -987,8 +988,9 @@ void main() { } return TableSpan( extent: const FixedTableSpanExtent(100.0), - backgroundDecoration: - color == null ? null : TableSpanDecoration(color: color), + backgroundDecoration: color == null + ? null + : TableSpanDecoration(color: color), ); }, ); @@ -1064,8 +1066,9 @@ void main() { } return TableSpan( extent: const FixedTableSpanExtent(100.0), - backgroundDecoration: - color == null ? null : TableSpanDecoration(color: color), + backgroundDecoration: color == null + ? null + : TableSpanDecoration(color: color), ); }, columnBuilder: (int index) { @@ -1077,8 +1080,9 @@ void main() { } return TableSpan( extent: const FixedTableSpanExtent(100.0), - backgroundDecoration: - color == null ? null : TableSpanDecoration(color: color), + backgroundDecoration: color == null + ? null + : TableSpanDecoration(color: color), ); }, ); @@ -1628,8 +1632,8 @@ void main() { child: Text('M(0,0)'), ); }, - columnBuilder: - (_) => const TableSpan(extent: FixedTableSpanExtent(100.0)), + columnBuilder: (_) => + const TableSpan(extent: FixedTableSpanExtent(100.0)), rowBuilder: (_) { return const TableSpan( extent: FixedTableSpanExtent(100.0), @@ -1657,8 +1661,8 @@ void main() { child: Text('M(0,0)'), ); }, - rowBuilder: - (_) => const TableSpan(extent: FixedTableSpanExtent(100.0)), + rowBuilder: (_) => + const TableSpan(extent: FixedTableSpanExtent(100.0)), columnBuilder: (_) { return const TableSpan( extent: FixedTableSpanExtent(100.0), diff --git a/packages/two_dimensional_scrollables/test/table_view/table_test.dart b/packages/two_dimensional_scrollables/test/table_view/table_test.dart index 6d0c1745208..8893edef189 100644 --- a/packages/two_dimensional_scrollables/test/table_view/table_test.dart +++ b/packages/two_dimensional_scrollables/test/table_view/table_test.dart @@ -2388,11 +2388,8 @@ void main() { rowCount: 50, columnCount: 50, columnBuilder: (_) => span, - rowBuilder: - (int index) => - index.isEven - ? getTappableSpan(index, () => tapCounter++) - : span, + rowBuilder: (int index) => + index.isEven ? getTappableSpan(index, () => tapCounter++) : span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: SizedBox.square( @@ -2433,11 +2430,8 @@ void main() { rowCount: 50, columnCount: 50, rowBuilder: (_) => span, - columnBuilder: - (int index) => - index.isEven - ? getTappableSpan(index, () => tapCounter++) - : span, + columnBuilder: (int index) => + index.isEven ? getTappableSpan(index, () => tapCounter++) : span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: SizedBox.square( @@ -2478,16 +2472,11 @@ void main() { tableView = TableView.builder( rowCount: 50, columnCount: 50, - rowBuilder: - (int index) => - index.isEven - ? getTappableSpan(index, () => rowTapCounter++) - : span, - columnBuilder: - (int index) => - index.isEven - ? getTappableSpan(index, () => columnTapCounter++) - : span, + rowBuilder: (int index) => + index.isEven ? getTappableSpan(index, () => rowTapCounter++) : span, + columnBuilder: (int index) => index.isEven + ? getTappableSpan(index, () => columnTapCounter++) + : span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: SizedBox.square( @@ -2535,16 +2524,11 @@ void main() { mainAxis: Axis.horizontal, rowCount: 50, columnCount: 50, - rowBuilder: - (int index) => - index.isEven - ? getTappableSpan(index, () => rowTapCounter++) - : span, - columnBuilder: - (int index) => - index.isEven - ? getTappableSpan(index, () => columnTapCounter++) - : span, + rowBuilder: (int index) => + index.isEven ? getTappableSpan(index, () => rowTapCounter++) : span, + columnBuilder: (int index) => index.isEven + ? getTappableSpan(index, () => columnTapCounter++) + : span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: SizedBox.square( @@ -2631,12 +2615,11 @@ void main() { TableView tableView = TableView.builder( rowCount: 50, columnCount: 50, - columnBuilder: - (_) => const TableSpan( - extent: FixedTableSpanExtent(100), - // This padding is so high, only the first column should be laid out. - padding: TableSpanPadding(leading: 2000), - ), + columnBuilder: (_) => const TableSpan( + extent: FixedTableSpanExtent(100), + // This padding is so high, only the first column should be laid out. + padding: TableSpanPadding(leading: 2000), + ), rowBuilder: (_) => span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( @@ -2666,11 +2649,10 @@ void main() { rowCount: 50, columnCount: 50, // This padding is so high, no children should be laid out. - rowBuilder: - (_) => const TableSpan( - extent: FixedTableSpanExtent(100), - padding: TableSpanPadding(leading: 2000), - ), + rowBuilder: (_) => const TableSpan( + extent: FixedTableSpanExtent(100), + padding: TableSpanPadding(leading: 2000), + ), columnBuilder: (_) => span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( @@ -2704,8 +2686,8 @@ void main() { TableView tableView = TableView.builder( rowCount: 50, columnCount: 50, - columnBuilder: - (_) => const TableSpan(extent: FixedTableSpanExtent(200)), + columnBuilder: (_) => + const TableSpan(extent: FixedTableSpanExtent(200)), rowBuilder: (_) => span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( @@ -2732,11 +2714,10 @@ void main() { tableView = TableView.builder( rowCount: 50, columnCount: 50, - columnBuilder: - (_) => const TableSpan( - extent: FixedTableSpanExtent(200), - padding: TableSpanPadding(trailing: 200), - ), + columnBuilder: (_) => const TableSpan( + extent: FixedTableSpanExtent(200), + padding: TableSpanPadding(trailing: 200), + ), rowBuilder: (_) => span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( @@ -2790,11 +2771,10 @@ void main() { tableView = TableView.builder( rowCount: 50, columnCount: 50, - rowBuilder: - (_) => const TableSpan( - extent: FixedTableSpanExtent(200), - padding: TableSpanPadding(trailing: 200), - ), + rowBuilder: (_) => const TableSpan( + extent: FixedTableSpanExtent(200), + padding: TableSpanPadding(trailing: 200), + ), columnBuilder: (_) => span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( @@ -3216,40 +3196,38 @@ void main() { TableView tableView = TableView.builder( rowCount: 2, columnCount: 2, - columnBuilder: - (int index) => TableSpan( - extent: const FixedTableSpanExtent(200.0), - padding: index == 0 ? const TableSpanPadding(trailing: 10) : null, - foregroundDecoration: TableSpanDecoration( - consumeSpanPadding: false, - borderRadius: BorderRadius.circular(10.0), - border: const TableSpanBorder( - trailing: BorderSide(color: Colors.orange, width: 3), - ), - ), - backgroundDecoration: TableSpanDecoration( - // consumePadding true by default - color: index.isEven ? Colors.red : null, - borderRadius: BorderRadius.circular(30.0), - ), + columnBuilder: (int index) => TableSpan( + extent: const FixedTableSpanExtent(200.0), + padding: index == 0 ? const TableSpanPadding(trailing: 10) : null, + foregroundDecoration: TableSpanDecoration( + consumeSpanPadding: false, + borderRadius: BorderRadius.circular(10.0), + border: const TableSpanBorder( + trailing: BorderSide(color: Colors.orange, width: 3), ), - rowBuilder: - (int index) => TableSpan( - extent: const FixedTableSpanExtent(200.0), - padding: index == 1 ? const TableSpanPadding(leading: 10) : null, - foregroundDecoration: TableSpanDecoration( - // consumePadding true by default - borderRadius: BorderRadius.circular(30.0), - border: const TableSpanBorder( - leading: BorderSide(color: Colors.green, width: 3), - ), - ), - backgroundDecoration: TableSpanDecoration( - color: index.isOdd ? Colors.blue : null, - borderRadius: BorderRadius.circular(30.0), - consumeSpanPadding: false, - ), + ), + backgroundDecoration: TableSpanDecoration( + // consumePadding true by default + color: index.isEven ? Colors.red : null, + borderRadius: BorderRadius.circular(30.0), + ), + ), + rowBuilder: (int index) => TableSpan( + extent: const FixedTableSpanExtent(200.0), + padding: index == 1 ? const TableSpanPadding(leading: 10) : null, + foregroundDecoration: TableSpanDecoration( + // consumePadding true by default + borderRadius: BorderRadius.circular(30.0), + border: const TableSpanBorder( + leading: BorderSide(color: Colors.green, width: 3), ), + ), + backgroundDecoration: TableSpanDecoration( + color: index.isOdd ? Colors.blue : null, + borderRadius: BorderRadius.circular(30.0), + consumeSpanPadding: false, + ), + ), cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: Container( @@ -3381,30 +3359,28 @@ void main() { mainAxis: Axis.horizontal, rowCount: 2, columnCount: 2, - columnBuilder: - (int index) => TableSpan( - extent: const FixedTableSpanExtent(200.0), - foregroundDecoration: const TableSpanDecoration( - border: TableSpanBorder( - trailing: BorderSide(color: Colors.orange, width: 3), - ), - ), - backgroundDecoration: TableSpanDecoration( - color: index.isEven ? Colors.red : null, - ), + columnBuilder: (int index) => TableSpan( + extent: const FixedTableSpanExtent(200.0), + foregroundDecoration: const TableSpanDecoration( + border: TableSpanBorder( + trailing: BorderSide(color: Colors.orange, width: 3), ), - rowBuilder: - (int index) => TableSpan( - extent: const FixedTableSpanExtent(200.0), - foregroundDecoration: const TableSpanDecoration( - border: TableSpanBorder( - leading: BorderSide(color: Colors.green, width: 3), - ), - ), - backgroundDecoration: TableSpanDecoration( - color: index.isOdd ? Colors.blue : null, - ), + ), + backgroundDecoration: TableSpanDecoration( + color: index.isEven ? Colors.red : null, + ), + ), + rowBuilder: (int index) => TableSpan( + extent: const FixedTableSpanExtent(200.0), + foregroundDecoration: const TableSpanDecoration( + border: TableSpanBorder( + leading: BorderSide(color: Colors.green, width: 3), ), + ), + backgroundDecoration: TableSpanDecoration( + color: index.isOdd ? Colors.blue : null, + ), + ), cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: Container( @@ -3501,10 +3477,10 @@ void main() { pinnedRowCount: 1, columnCount: 2, pinnedColumnCount: 1, - columnBuilder: - (int index) => const TableSpan(extent: FixedTableSpanExtent(200.0)), - rowBuilder: - (int index) => const TableSpan(extent: FixedTableSpanExtent(200.0)), + columnBuilder: (int index) => + const TableSpan(extent: FixedTableSpanExtent(200.0)), + rowBuilder: (int index) => + const TableSpan(extent: FixedTableSpanExtent(200.0)), cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: Container( @@ -3547,10 +3523,10 @@ void main() { pinnedRowCount: 1, columnCount: 2, pinnedColumnCount: 1, - columnBuilder: - (int index) => const TableSpan(extent: FixedTableSpanExtent(200.0)), - rowBuilder: - (int index) => const TableSpan(extent: FixedTableSpanExtent(200.0)), + columnBuilder: (int index) => + const TableSpan(extent: FixedTableSpanExtent(200.0)), + rowBuilder: (int index) => + const TableSpan(extent: FixedTableSpanExtent(200.0)), cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: Container( @@ -3593,15 +3569,13 @@ void main() { rowCount: 50, columnCount: 50, columnBuilder: (_) => span, - rowBuilder: - (int index) => - index.isEven - ? getMouseTrackingSpan( - index, - onEnter: (_) => enterCounter++, - onExit: (_) => exitCounter++, - ) - : span, + rowBuilder: (int index) => index.isEven + ? getMouseTrackingSpan( + index, + onEnter: (_) => enterCounter++, + onExit: (_) => exitCounter++, + ) + : span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: SizedBox.square( @@ -4136,8 +4110,8 @@ void main() { final TableView tableView = TableView.builder( columnCount: 10, rowCount: 10, - columnBuilder: - (_) => const TableSpan(extent: FixedTableSpanExtent(100)), + columnBuilder: (_) => + const TableSpan(extent: FixedTableSpanExtent(100)), rowBuilder: (_) => const TableSpan(extent: FixedTableSpanExtent(100)), cellBuilder: (BuildContext context, TableVicinity vicinity) { if (mergedCell.contains(vicinity)) { diff --git a/packages/two_dimensional_scrollables/test/tree_view/render_tree_test.dart b/packages/two_dimensional_scrollables/test/tree_view/render_tree_test.dart index 3836f36b49d..f3f4b9ba204 100644 --- a/packages/two_dimensional_scrollables/test/tree_view/render_tree_test.dart +++ b/packages/two_dimensional_scrollables/test/tree_view/render_tree_test.dart @@ -87,8 +87,8 @@ void main() { delegate: TreeRowBuilderDelegate( rowCount: 0, nodeBuilder: (_, __) => const SizedBox(), - rowBuilder: - (_) => const TreeRow(extent: FixedTreeRowExtent(40.0)), + rowBuilder: (_) => + const TreeRow(extent: FixedTreeRowExtent(40.0)), ), activeAnimations: const {}, rowDepths: const {}, @@ -114,8 +114,8 @@ void main() { delegate: TreeRowBuilderDelegate( rowCount: 0, nodeBuilder: (_, __) => const SizedBox(), - rowBuilder: - (_) => const TreeRow(extent: FixedTreeRowExtent(40.0)), + rowBuilder: (_) => + const TreeRow(extent: FixedTreeRowExtent(40.0)), ), activeAnimations: const {}, rowDepths: const {}, @@ -721,14 +721,12 @@ void main() { tree: treeNodes, treeRowBuilder: (TreeViewNode node) { return row.copyWith( - backgroundDecoration: - node.depth! == 0 - ? rootBackgroundDecoration - : backgroundDecoration, - foregroundDecoration: - node.depth! == 0 - ? rootForegroundDecoration - : foregroundDecoration, + backgroundDecoration: node.depth! == 0 + ? rootBackgroundDecoration + : backgroundDecoration, + foregroundDecoration: node.depth! == 0 + ? rootForegroundDecoration + : foregroundDecoration, ); }, ); diff --git a/packages/two_dimensional_scrollables/test/tree_view/tree_test.dart b/packages/two_dimensional_scrollables/test/tree_view/tree_test.dart index 720ad7b34a5..0bc08e8ed3b 100644 --- a/packages/two_dimensional_scrollables/test/tree_view/tree_test.dart +++ b/packages/two_dimensional_scrollables/test/tree_view/tree_test.dart @@ -128,18 +128,19 @@ void main() { home: TreeView( tree: simpleNodeSet, controller: controller, - treeNodeBuilder: ( - BuildContext context, - TreeViewNode node, - AnimationStyle toggleAnimationStyle, - ) { - returnedController ??= TreeViewController.of(context); - return TreeView.defaultTreeNodeBuilder( - context, - node, - toggleAnimationStyle, - ); - }, + treeNodeBuilder: + ( + BuildContext context, + TreeViewNode node, + AnimationStyle toggleAnimationStyle, + ) { + returnedController ??= TreeViewController.of(context); + return TreeView.defaultTreeNodeBuilder( + context, + node, + toggleAnimationStyle, + ); + }, ), ), ); @@ -154,18 +155,19 @@ void main() { MaterialApp( home: TreeView( tree: simpleNodeSet, - treeNodeBuilder: ( - BuildContext context, - TreeViewNode node, - AnimationStyle toggleAnimationStyle, - ) { - returnedController ??= TreeViewController.maybeOf(context); - return TreeView.defaultTreeNodeBuilder( - context, - node, - toggleAnimationStyle, - ); - }, + treeNodeBuilder: + ( + BuildContext context, + TreeViewNode node, + AnimationStyle toggleAnimationStyle, + ) { + returnedController ??= TreeViewController.maybeOf(context); + return TreeView.defaultTreeNodeBuilder( + context, + node, + toggleAnimationStyle, + ); + }, ), ), ); @@ -411,45 +413,49 @@ void main() { toggled = true; toggledNode = node; }, - treeNodeBuilder: ( - BuildContext context, - TreeViewNode node, - AnimationStyle toggleAnimationStyle, - ) { - final Duration animationDuration = - toggleAnimationStyle.duration ?? - TreeView.defaultAnimationDuration; - final Curve animationCurve = - toggleAnimationStyle.curve ?? TreeView.defaultAnimationCurve; - // This makes the whole row trigger toggling. - return TreeView.wrapChildToToggleNode( - node: node, - child: Padding( - padding: const EdgeInsets.all(8.0), - child: Row( - children: [ - // Icon for parent nodes - SizedBox.square( - dimension: 30.0, - child: - node.children.isNotEmpty + treeNodeBuilder: + ( + BuildContext context, + TreeViewNode node, + AnimationStyle toggleAnimationStyle, + ) { + final Duration animationDuration = + toggleAnimationStyle.duration ?? + TreeView.defaultAnimationDuration; + final Curve animationCurve = + toggleAnimationStyle.curve ?? + TreeView.defaultAnimationCurve; + // This makes the whole row trigger toggling. + return TreeView.wrapChildToToggleNode( + node: node, + child: Padding( + padding: const EdgeInsets.all(8.0), + child: Row( + children: [ + // Icon for parent nodes + SizedBox.square( + dimension: 30.0, + child: node.children.isNotEmpty ? AnimatedRotation( - turns: node.isExpanded ? 0.25 : 0.0, - duration: animationDuration, - curve: animationCurve, - child: const Icon(IconData(0x25BA), size: 14), - ) + turns: node.isExpanded ? 0.25 : 0.0, + duration: animationDuration, + curve: animationCurve, + child: const Icon( + IconData(0x25BA), + size: 14, + ), + ) : null, + ), + // Spacer + const SizedBox(width: 8.0), + // Content + Text(node.content), + ], ), - // Spacer - const SizedBox(width: 8.0), - // Content - Text(node.content), - ], - ), - ), - ); - }, + ), + ); + }, ), ), ); @@ -471,14 +477,15 @@ void main() { MaterialApp( home: TreeView( tree: simpleNodeSet, - treeNodeBuilder: ( - BuildContext context, - TreeViewNode node, - AnimationStyle toggleAnimationStyle, - ) { - style ??= toggleAnimationStyle; - return Text(node.content); - }, + treeNodeBuilder: + ( + BuildContext context, + TreeViewNode node, + AnimationStyle toggleAnimationStyle, + ) { + style ??= toggleAnimationStyle; + return Text(node.content); + }, ), ), ); @@ -497,14 +504,15 @@ void main() { home: TreeView( tree: simpleNodeSet, toggleAnimationStyle: AnimationStyle.noAnimation, - treeNodeBuilder: ( - BuildContext context, - TreeViewNode node, - AnimationStyle toggleAnimationStyle, - ) { - style = toggleAnimationStyle; - return Text(node.content); - }, + treeNodeBuilder: + ( + BuildContext context, + TreeViewNode node, + AnimationStyle toggleAnimationStyle, + ) { + style = toggleAnimationStyle; + return Text(node.content); + }, ), ), ); @@ -522,14 +530,15 @@ void main() { curve: Curves.easeIn, duration: const Duration(milliseconds: 200), ), - treeNodeBuilder: ( - BuildContext context, - TreeViewNode node, - AnimationStyle toggleAnimationStyle, - ) { - style ??= toggleAnimationStyle; - return Text(node.content); - }, + treeNodeBuilder: + ( + BuildContext context, + TreeViewNode node, + AnimationStyle toggleAnimationStyle, + ) { + style ??= toggleAnimationStyle; + return Text(node.content); + }, ), ), ); @@ -648,13 +657,18 @@ void main() { test('should use the generic type for callbacks and builders', () { final TreeView treeView = TreeView( tree: simpleNodeSet, - treeNodeBuilder: ( - BuildContext context, - TreeViewNode node, - AnimationStyle animationStyle, - ) { - return TreeView.defaultTreeNodeBuilder(context, node, animationStyle); - }, + treeNodeBuilder: + ( + BuildContext context, + TreeViewNode node, + AnimationStyle animationStyle, + ) { + return TreeView.defaultTreeNodeBuilder( + context, + node, + animationStyle, + ); + }, treeRowBuilder: (TreeViewNode node) { return TreeView.defaultTreeRowBuilder(node); }, @@ -710,23 +724,24 @@ void main() { curve: Curves.easeInOut, duration: Duration.zero, ), - treeNodeBuilder: ( - BuildContext context, - TreeViewNode node, - AnimationStyle animationStyle, - ) { - final Widget child = GestureDetector( - behavior: HitTestBehavior.translucent, - onTap: () => controller.toggleNode(node), - child: TreeView.defaultTreeNodeBuilder( - context, - node, - animationStyle, - ), - ); + treeNodeBuilder: + ( + BuildContext context, + TreeViewNode node, + AnimationStyle animationStyle, + ) { + final Widget child = GestureDetector( + behavior: HitTestBehavior.translucent, + onTap: () => controller.toggleNode(node), + child: TreeView.defaultTreeNodeBuilder( + context, + node, + animationStyle, + ), + ); - return child; - }, + return child; + }, ), ), ); @@ -800,23 +815,24 @@ void main() { curve: Curves.easeInOut, duration: const Duration(milliseconds: 200), ), - treeNodeBuilder: ( - BuildContext context, - TreeViewNode node, - AnimationStyle animationStyle, - ) { - final Widget child = GestureDetector( - behavior: HitTestBehavior.translucent, - onTap: () => controller.toggleNode(node), - child: TreeView.defaultTreeNodeBuilder( - context, - node, - animationStyle, - ), - ); + treeNodeBuilder: + ( + BuildContext context, + TreeViewNode node, + AnimationStyle animationStyle, + ) { + final Widget child = GestureDetector( + behavior: HitTestBehavior.translucent, + onTap: () => controller.toggleNode(node), + child: TreeView.defaultTreeNodeBuilder( + context, + node, + animationStyle, + ), + ); - return child; - }, + return child; + }, ), ), ); @@ -945,8 +961,8 @@ void main() { delegate: TreeRowBuilderDelegate( rowCount: 0, nodeBuilder: (_, __) => const SizedBox(), - rowBuilder: - (_) => const TreeRow(extent: FixedTreeRowExtent(40.0)), + rowBuilder: (_) => + const TreeRow(extent: FixedTreeRowExtent(40.0)), ), activeAnimations: const {}, rowDepths: const {}, @@ -971,8 +987,8 @@ void main() { delegate: TreeRowBuilderDelegate( rowCount: 0, nodeBuilder: (_, __) => const SizedBox(), - rowBuilder: - (_) => const TreeRow(extent: FixedTreeRowExtent(40.0)), + rowBuilder: (_) => + const TreeRow(extent: FixedTreeRowExtent(40.0)), ), activeAnimations: const {}, rowDepths: const {}, diff --git a/packages/url_launcher/url_launcher/CHANGELOG.md b/packages/url_launcher/url_launcher/CHANGELOG.md index 920a7ad8e78..a4af9cc5d48 100644 --- a/packages/url_launcher/url_launcher/CHANGELOG.md +++ b/packages/url_launcher/url_launcher/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 6.3.2 diff --git a/packages/url_launcher/url_launcher/example/lib/main.dart b/packages/url_launcher/url_launcher/example/lib/main.dart index a9de087a2c3..61f17104b55 100644 --- a/packages/url_launcher/url_launcher/example/lib/main.dart +++ b/packages/url_launcher/url_launcher/example/lib/main.dart @@ -160,86 +160,74 @@ class _MyHomePageState extends State { ), ), ElevatedButton( - onPressed: - _hasCallSupport - ? () => setState(() { - _launched = _makePhoneCall(_phone); - }) - : null, - child: - _hasCallSupport - ? const Text('Make phone call') - : const Text('Calling not supported'), + onPressed: _hasCallSupport + ? () => setState(() { + _launched = _makePhoneCall(_phone); + }) + : null, + child: _hasCallSupport + ? const Text('Make phone call') + : const Text('Calling not supported'), ), Padding( padding: const EdgeInsets.all(16.0), child: Text(toLaunch.toString()), ), ElevatedButton( - onPressed: - () => setState(() { - _launched = _launchInBrowser(toLaunch); - }), + onPressed: () => setState(() { + _launched = _launchInBrowser(toLaunch); + }), child: const Text('Launch in browser'), ), const Padding(padding: EdgeInsets.all(16.0)), ElevatedButton( - onPressed: - () => setState(() { - _launched = _launchInBrowserView(toLaunch); - }), + onPressed: () => setState(() { + _launched = _launchInBrowserView(toLaunch); + }), child: const Text('Launch in app'), ), ElevatedButton( - onPressed: - () => setState(() { - _launched = _launchAsInAppWebViewWithCustomHeaders( - toLaunch, - ); - }), + onPressed: () => setState(() { + _launched = _launchAsInAppWebViewWithCustomHeaders(toLaunch); + }), child: const Text('Launch in app (Custom Headers)'), ), ElevatedButton( - onPressed: - () => setState(() { - _launched = _launchInWebViewWithoutJavaScript(toLaunch); - }), + onPressed: () => setState(() { + _launched = _launchInWebViewWithoutJavaScript(toLaunch); + }), child: const Text('Launch in app (JavaScript OFF)'), ), ElevatedButton( - onPressed: - () => setState(() { - _launched = _launchInWebViewWithoutDomStorage(toLaunch); - }), + onPressed: () => setState(() { + _launched = _launchInWebViewWithoutDomStorage(toLaunch); + }), child: const Text('Launch in app (DOM storage OFF)'), ), const Padding(padding: EdgeInsets.all(16.0)), ElevatedButton( - onPressed: - () => setState(() { - _launched = _launchUniversalLinkIOS(toLaunch); - }), + onPressed: () => setState(() { + _launched = _launchUniversalLinkIOS(toLaunch); + }), child: const Text( 'Launch a universal link in a native app, fallback to Safari.(Youtube)', ), ), const Padding(padding: EdgeInsets.all(16.0)), ElevatedButton( - onPressed: - () => setState(() { - _launched = _launchInWebView(toLaunch); - Timer(const Duration(seconds: 5), () { - closeInAppWebView(); - }); - }), + onPressed: () => setState(() { + _launched = _launchInWebView(toLaunch); + Timer(const Duration(seconds: 5), () { + closeInAppWebView(); + }); + }), child: const Text('Launch in app + close after 5 seconds'), ), const Padding(padding: EdgeInsets.all(16.0)), ElevatedButton( - onPressed: - () => setState(() { - _launched = _launchInAppWithBrowserOptions(toLaunch); - }), + onPressed: () => setState(() { + _launched = _launchInAppWithBrowserOptions(toLaunch); + }), child: const Text('Launch in app with title displayed'), ), const Padding(padding: EdgeInsets.all(16.0)), diff --git a/packages/url_launcher/url_launcher/example/pubspec.yaml b/packages/url_launcher/url_launcher/example/pubspec.yaml index 6b64e933cb1..b3b36ef21ca 100644 --- a/packages/url_launcher/url_launcher/example/pubspec.yaml +++ b/packages/url_launcher/url_launcher/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the url_launcher plugin. publish_to: none environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/url_launcher/url_launcher/lib/src/legacy_api.dart b/packages/url_launcher/url_launcher/lib/src/legacy_api.dart index 6b94e39c1cc..60727c35162 100644 --- a/packages/url_launcher/url_launcher/lib/src/legacy_api.dart +++ b/packages/url_launcher/url_launcher/lib/src/legacy_api.dart @@ -91,8 +91,8 @@ Future launch( bool previousAutomaticSystemUiAdjustment = true; final RenderView? renderViewToAdjust = statusBarBrightness != null && defaultTargetPlatform == TargetPlatform.iOS - ? _findImplicitRenderView() - : null; + ? _findImplicitRenderView() + : null; if (renderViewToAdjust != null) { previousAutomaticSystemUiAdjustment = renderViewToAdjust.automaticSystemUiAdjustment; diff --git a/packages/url_launcher/url_launcher/lib/src/link.dart b/packages/url_launcher/url_launcher/lib/src/link.dart index 6445de68852..95f315beb39 100644 --- a/packages/url_launcher/url_launcher/lib/src/link.dart +++ b/packages/url_launcher/url_launcher/lib/src/link.dart @@ -125,10 +125,9 @@ class DefaultLinkDelegate extends StatelessWidget { try { success = await launchUrl( url, - mode: - _useWebView - ? LaunchMode.inAppBrowserView - : LaunchMode.externalApplication, + mode: _useWebView + ? LaunchMode.inAppBrowserView + : LaunchMode.externalApplication, ); } on PlatformException { success = false; diff --git a/packages/url_launcher/url_launcher/pubspec.yaml b/packages/url_launcher/url_launcher/pubspec.yaml index 1dbe073249a..4d7d2077baf 100644 --- a/packages/url_launcher/url_launcher/pubspec.yaml +++ b/packages/url_launcher/url_launcher/pubspec.yaml @@ -6,8 +6,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 6.3.2 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" flutter: plugin: diff --git a/packages/url_launcher/url_launcher/test/link_test.dart b/packages/url_launcher/url_launcher/test/link_test.dart index 31e5b1889d1..ad89cac7139 100644 --- a/packages/url_launcher/url_launcher/test/link_test.dart +++ b/packages/url_launcher/url_launcher/test/link_test.dart @@ -118,14 +118,13 @@ void main() { await tester.pumpWidget( MaterialApp( routes: { - '/': - (BuildContext context) => Link( - uri: uri, - builder: (BuildContext context, FollowLink? followLink2) { - followLink = followLink2; - return Container(); - }, - ), + '/': (BuildContext context) => Link( + uri: uri, + builder: (BuildContext context, FollowLink? followLink2) { + followLink = followLink2; + return Container(); + }, + ), '/foo/bar': (BuildContext context) => Container(), }, ), diff --git a/packages/url_launcher/url_launcher_linux/CHANGELOG.md b/packages/url_launcher/url_launcher_linux/CHANGELOG.md index 45b0a2c1dca..3c1e0e55e10 100644 --- a/packages/url_launcher/url_launcher_linux/CHANGELOG.md +++ b/packages/url_launcher/url_launcher_linux/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 3.2.1 diff --git a/packages/url_launcher/url_launcher_linux/example/lib/main.dart b/packages/url_launcher/url_launcher_linux/example/lib/main.dart index 29a4588e519..e8d91be181d 100644 --- a/packages/url_launcher/url_launcher_linux/example/lib/main.dart +++ b/packages/url_launcher/url_launcher_linux/example/lib/main.dart @@ -75,10 +75,9 @@ class _MyHomePageState extends State { child: Text(toLaunch), ), ElevatedButton( - onPressed: - () => setState(() { - _launched = _launchInBrowser(toLaunch); - }), + onPressed: () => setState(() { + _launched = _launchInBrowser(toLaunch); + }), child: const Text('Launch in browser'), ), const Padding(padding: EdgeInsets.all(16.0)), diff --git a/packages/url_launcher/url_launcher_linux/example/pubspec.yaml b/packages/url_launcher/url_launcher_linux/example/pubspec.yaml index 264b77c645e..bba98221701 100644 --- a/packages/url_launcher/url_launcher_linux/example/pubspec.yaml +++ b/packages/url_launcher/url_launcher_linux/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the url_launcher plugin. publish_to: none environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/url_launcher/url_launcher_linux/lib/src/messages.g.dart b/packages/url_launcher/url_launcher_linux/lib/src/messages.g.dart index 6683d00f17e..0a254a59feb 100644 --- a/packages/url_launcher/url_launcher_linux/lib/src/messages.g.dart +++ b/packages/url_launcher/url_launcher_linux/lib/src/messages.g.dart @@ -47,8 +47,9 @@ class UrlLauncherApi { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); diff --git a/packages/url_launcher/url_launcher_linux/pubspec.yaml b/packages/url_launcher/url_launcher_linux/pubspec.yaml index c4bc2bca850..4430f8c64d0 100644 --- a/packages/url_launcher/url_launcher_linux/pubspec.yaml +++ b/packages/url_launcher/url_launcher_linux/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 3.2.1 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" flutter: plugin: diff --git a/packages/url_launcher/url_launcher_platform_interface/CHANGELOG.md b/packages/url_launcher/url_launcher_platform_interface/CHANGELOG.md index 9f210e84e94..5f425ecf091 100644 --- a/packages/url_launcher/url_launcher_platform_interface/CHANGELOG.md +++ b/packages/url_launcher/url_launcher_platform_interface/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 2.3.2 diff --git a/packages/url_launcher/url_launcher_platform_interface/pubspec.yaml b/packages/url_launcher/url_launcher_platform_interface/pubspec.yaml index e7a0682b1ee..7e1dda12816 100644 --- a/packages/url_launcher/url_launcher_platform_interface/pubspec.yaml +++ b/packages/url_launcher/url_launcher_platform_interface/pubspec.yaml @@ -7,8 +7,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.3.2 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/url_launcher/url_launcher_web/CHANGELOG.md b/packages/url_launcher/url_launcher_web/CHANGELOG.md index 6c3c1b01071..bf73761336c 100644 --- a/packages/url_launcher/url_launcher_web/CHANGELOG.md +++ b/packages/url_launcher/url_launcher_web/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 2.4.1 diff --git a/packages/url_launcher/url_launcher_web/example/integration_test/link_widget_test.dart b/packages/url_launcher/url_launcher_web/example/integration_test/link_widget_test.dart index 1ce00fc992e..d50ec191e71 100644 --- a/packages/url_launcher/url_launcher_web/example/integration_test/link_widget_test.dart +++ b/packages/url_launcher/url_launcher_web/example/integration_test/link_widget_test.dart @@ -184,16 +184,14 @@ void main() { data: const MediaQueryData(), child: ListView.builder( itemCount: itemCount, - itemBuilder: - (_, int index) => WebLinkDelegate( - TestLinkInfo( - uri: uri, - target: LinkTarget.defaultTarget, - builder: - (BuildContext context, FollowLink? followLink) => - Text('#$index', textAlign: TextAlign.center), - ), - ), + itemBuilder: (_, int index) => WebLinkDelegate( + TestLinkInfo( + uri: uri, + target: LinkTarget.defaultTarget, + builder: (BuildContext context, FollowLink? followLink) => + Text('#$index', textAlign: TextAlign.center), + ), + ), ), ), ), @@ -396,10 +394,10 @@ void main() { await tester.pumpWidget( MaterialApp( routes: { - '/foobar1': - (BuildContext context) => const Text('Internal route 1'), - '/foobar2': - (BuildContext context) => const Text('Internal route 2'), + '/foobar1': (BuildContext context) => + const Text('Internal route 1'), + '/foobar2': (BuildContext context) => + const Text('Internal route 2'), }, home: Column( children: [ @@ -992,11 +990,10 @@ void main() { 'flt-semantics-host', ); html.document.body!.append(semanticsHost); - final html.Element semanticsAnchor = - html.document.createElement('a') - ..setAttribute('id', 'flt-semantic-node-99') - ..setAttribute('flt-semantics-identifier', 'test-link-27') - ..setAttribute('href', '/foobar'); + final html.Element semanticsAnchor = html.document.createElement('a') + ..setAttribute('id', 'flt-semantic-node-99') + ..setAttribute('flt-semantics-identifier', 'test-link-27') + ..setAttribute('href', '/foobar'); semanticsHost.append(semanticsAnchor); final html.Element semanticsContainer = html.document.createElement( 'flt-semantics-container', @@ -1064,12 +1061,11 @@ void main() { 'flt-semantics-host', ); html.document.body!.append(semanticsHost); - final html.Element semanticsAnchor = - html.document.createElement('a') - ..setAttribute('id', 'flt-semantic-node-99') - ..setAttribute('flt-semantics-identifier', 'test-link-71') - ..setAttribute('href', '/foobar') - ..textContent = 'My Text Link'; + final html.Element semanticsAnchor = html.document.createElement('a') + ..setAttribute('id', 'flt-semantic-node-99') + ..setAttribute('flt-semantics-identifier', 'test-link-71') + ..setAttribute('href', '/foobar') + ..textContent = 'My Text Link'; semanticsHost.append(semanticsAnchor); expect(pushedRouteNames, isEmpty); @@ -1115,12 +1111,11 @@ void main() { 'flt-semantics-host', ); html.document.body!.append(semanticsHost); - final html.Element semanticsAnchor = - html.document.createElement('a') - ..setAttribute('id', 'flt-semantic-node-99') - ..setAttribute('flt-semantics-identifier', 'test-link-71') - ..setAttribute('href', uri.toString()) - ..textContent = 'My Text Link'; + final html.Element semanticsAnchor = html.document.createElement('a') + ..setAttribute('id', 'flt-semantic-node-99') + ..setAttribute('flt-semantics-identifier', 'test-link-71') + ..setAttribute('href', uri.toString()) + ..textContent = 'My Text Link'; semanticsHost.append(semanticsAnchor); expect(pushedRouteNames, isEmpty); @@ -1172,12 +1167,11 @@ void main() { 'flt-semantics-host', ); html.document.body!.append(semanticsHost); - final html.Element semanticsAnchor = - html.document.createElement('a') - ..setAttribute('id', 'flt-semantic-node-99') - ..setAttribute('flt-semantics-identifier', 'test-link-71') - ..setAttribute('href', uri.toString()) - ..textContent = 'My Text Link'; + final html.Element semanticsAnchor = html.document.createElement('a') + ..setAttribute('id', 'flt-semantic-node-99') + ..setAttribute('flt-semantics-identifier', 'test-link-71') + ..setAttribute('href', uri.toString()) + ..textContent = 'My Text Link'; semanticsHost.append(semanticsAnchor); expect(pushedRouteNames, isEmpty); @@ -1229,10 +1223,9 @@ void main() { 'flt-semantics-host', ); html.document.body!.append(semanticsHost); - final html.Element semanticsAnchor = - html.document.createElement('a') - ..setAttribute('id', 'flt-semantic-node-99') - ..setAttribute('href', '#'); + final html.Element semanticsAnchor = html.document.createElement('a') + ..setAttribute('id', 'flt-semantic-node-99') + ..setAttribute('href', '#'); semanticsHost.append(semanticsAnchor); final html.Element semanticsContainer = html.document.createElement( 'flt-semantics-container', @@ -1293,11 +1286,10 @@ void main() { 'flt-semantics-host', ); html.document.body!.append(semanticsHost); - final html.Element semanticsAnchor = - html.document.createElement('a') - ..setAttribute('id', 'flt-semantic-node-99') - ..setAttribute('href', '#') - ..textContent = 'My Text Link'; + final html.Element semanticsAnchor = html.document.createElement('a') + ..setAttribute('id', 'flt-semantic-node-99') + ..setAttribute('href', '#') + ..textContent = 'My Text Link'; semanticsHost.append(semanticsAnchor); expect(pushedRouteNames, isEmpty); diff --git a/packages/url_launcher/url_launcher_web/example/pubspec.yaml b/packages/url_launcher/url_launcher_web/example/pubspec.yaml index 586ae6e6fa1..2ac69f10b3a 100644 --- a/packages/url_launcher/url_launcher_web/example/pubspec.yaml +++ b/packages/url_launcher/url_launcher_web/example/pubspec.yaml @@ -2,8 +2,8 @@ name: regular_integration_tests publish_to: none environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/url_launcher/url_launcher_web/lib/src/link.dart b/packages/url_launcher/url_launcher_web/lib/src/link.dart index a2ba70d77e3..502157c0d4d 100644 --- a/packages/url_launcher/url_launcher_web/lib/src/link.dart +++ b/packages/url_launcher/url_launcher_web/lib/src/link.dart @@ -142,17 +142,15 @@ class WebLinkDelegateState extends State { ..setUri(widget.link.uri) ..setTarget(widget.link.target); }, - surfaceFactory: ( - BuildContext context, - PlatformViewController controller, - ) { - return PlatformViewSurface( - controller: controller, - gestureRecognizers: - const >{}, - hitTestBehavior: PlatformViewHitTestBehavior.transparent, - ); - }, + surfaceFactory: + (BuildContext context, PlatformViewController controller) { + return PlatformViewSurface( + controller: controller, + gestureRecognizers: + const >{}, + hitTestBehavior: PlatformViewHitTestBehavior.transparent, + ); + }, ), ), ); diff --git a/packages/url_launcher/url_launcher_web/pubspec.yaml b/packages/url_launcher/url_launcher_web/pubspec.yaml index 820e20f349d..43671b835b8 100644 --- a/packages/url_launcher/url_launcher_web/pubspec.yaml +++ b/packages/url_launcher/url_launcher_web/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.4.1 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" flutter: plugin: diff --git a/packages/url_launcher/url_launcher_windows/CHANGELOG.md b/packages/url_launcher/url_launcher_windows/CHANGELOG.md index 9e49e72706e..67a70ef985e 100644 --- a/packages/url_launcher/url_launcher_windows/CHANGELOG.md +++ b/packages/url_launcher/url_launcher_windows/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 3.1.4 diff --git a/packages/url_launcher/url_launcher_windows/example/lib/main.dart b/packages/url_launcher/url_launcher_windows/example/lib/main.dart index 29a4588e519..e8d91be181d 100644 --- a/packages/url_launcher/url_launcher_windows/example/lib/main.dart +++ b/packages/url_launcher/url_launcher_windows/example/lib/main.dart @@ -75,10 +75,9 @@ class _MyHomePageState extends State { child: Text(toLaunch), ), ElevatedButton( - onPressed: - () => setState(() { - _launched = _launchInBrowser(toLaunch); - }), + onPressed: () => setState(() { + _launched = _launchInBrowser(toLaunch); + }), child: const Text('Launch in browser'), ), const Padding(padding: EdgeInsets.all(16.0)), diff --git a/packages/url_launcher/url_launcher_windows/example/pubspec.yaml b/packages/url_launcher/url_launcher_windows/example/pubspec.yaml index 5b558573268..beeff708b04 100644 --- a/packages/url_launcher/url_launcher_windows/example/pubspec.yaml +++ b/packages/url_launcher/url_launcher_windows/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates the Windows implementation of the url_launcher plugin. publish_to: none environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/url_launcher/url_launcher_windows/lib/src/messages.g.dart b/packages/url_launcher/url_launcher_windows/lib/src/messages.g.dart index 161c476344f..8f24cc48c7d 100644 --- a/packages/url_launcher/url_launcher_windows/lib/src/messages.g.dart +++ b/packages/url_launcher/url_launcher_windows/lib/src/messages.g.dart @@ -30,8 +30,9 @@ class UrlLauncherApi { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) : __pigeon_binaryMessenger = binaryMessenger, - __pigeon_messageChannelSuffix = - messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + __pigeon_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? __pigeon_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); diff --git a/packages/url_launcher/url_launcher_windows/pubspec.yaml b/packages/url_launcher/url_launcher_windows/pubspec.yaml index 53671a8ade0..c06c6a2f327 100644 --- a/packages/url_launcher/url_launcher_windows/pubspec.yaml +++ b/packages/url_launcher/url_launcher_windows/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 3.1.4 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" flutter: plugin: diff --git a/packages/vector_graphics/CHANGELOG.md b/packages/vector_graphics/CHANGELOG.md index 50750c89b27..b01cb1ae3c2 100644 --- a/packages/vector_graphics/CHANGELOG.md +++ b/packages/vector_graphics/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 1.1.19 diff --git a/packages/vector_graphics/example/pubspec.yaml b/packages/vector_graphics/example/pubspec.yaml index af4a00c804a..60752dd1cca 100644 --- a/packages/vector_graphics/example/pubspec.yaml +++ b/packages/vector_graphics/example/pubspec.yaml @@ -3,7 +3,7 @@ description: An example of the vector_graphics package publish_to: 'none' environment: - sdk: ^3.7.0 + sdk: ^3.8.0 dependencies: flutter: diff --git a/packages/vector_graphics/lib/src/listener.dart b/packages/vector_graphics/lib/src/listener.dart index 7c2f208f413..eb32775386d 100644 --- a/packages/vector_graphics/lib/src/listener.dart +++ b/packages/vector_graphics/lib/src/listener.dart @@ -114,32 +114,30 @@ Future decodeVectorGraphics( return Zone.current .fork( specification: ZoneSpecification( - scheduleMicrotask: ( - Zone self, - ZoneDelegate parent, - Zone zone, - void Function() f, - ) { - Zone.root.scheduleMicrotask(f); - }, - createTimer: ( - Zone self, - ZoneDelegate parent, - Zone zone, - Duration duration, - void Function() f, - ) { - return Zone.root.createTimer(duration, f); - }, - createPeriodicTimer: ( - Zone self, - ZoneDelegate parent, - Zone zone, - Duration period, - void Function(Timer timer) f, - ) { - return Zone.root.createPeriodicTimer(period, f); - }, + scheduleMicrotask: + (Zone self, ZoneDelegate parent, Zone zone, void Function() f) { + Zone.root.scheduleMicrotask(f); + }, + createTimer: + ( + Zone self, + ZoneDelegate parent, + Zone zone, + Duration duration, + void Function() f, + ) { + return Zone.root.createTimer(duration, f); + }, + createPeriodicTimer: + ( + Zone self, + ZoneDelegate parent, + Zone zone, + Duration period, + void Function(Timer timer) f, + ) { + return Zone.root.createPeriodicTimer(period, f); + }, ), ) .run>(process); @@ -280,17 +278,16 @@ class FlutterVectorGraphicsListener extends VectorGraphicsCodecListener { _PatternConfig? _currentPattern; static final Paint _emptyPaint = Paint(); - static final Paint _grayscaleDstInPaint = - Paint() - ..blendMode = BlendMode.dstIn - ..colorFilter = const ColorFilter.matrix( - [ - 0, 0, 0, 0, 0, // - 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, - 0.2126, 0.7152, 0.0722, 0, 0, - ], - ); //convert to grayscale (https://www.w3.org/Graphics/Color/sRGB) and use them as transparency + static final Paint _grayscaleDstInPaint = Paint() + ..blendMode = BlendMode.dstIn + ..colorFilter = const ColorFilter.matrix( + [ + 0, 0, 0, 0, 0, // + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0.2126, 0.7152, 0.0722, 0, 0, + ], + ); //convert to grayscale (https://www.w3.org/Graphics/Color/sRGB) and use them as transparency /// Convert the vector graphics asset this listener decoded into a [Picture]. /// @@ -487,10 +484,9 @@ class FlutterVectorGraphicsListener extends VectorGraphicsCodecListener { final PictureRecorder recorder = _pictureFactory.createPictureRecorder(); final Canvas newCanvas = _pictureFactory.createCanvas(recorder); newCanvas.clipRect(Offset(x, y) & Size(width, height)); - _patterns[patternId] = - _PatternState() - ..recorder = recorder - ..canvas = newCanvas; + _patterns[patternId] = _PatternState() + ..recorder = recorder + ..canvas = newCanvas; } /// Creates ImageShader for active pattern. diff --git a/packages/vector_graphics/lib/src/render_vector_graphic.dart b/packages/vector_graphics/lib/src/render_vector_graphic.dart index d2fe579ce31..78e8bd6c621 100644 --- a/packages/vector_graphics/lib/src/render_vector_graphic.dart +++ b/packages/vector_graphics/lib/src/render_vector_graphic.dart @@ -236,8 +236,8 @@ class RenderVectorGraphic extends RenderBox { // is sufficiently different. Returns `null` if rasterData has been // updated immediately. void _maybeUpdateRaster() { - final int scaledWidth = - (pictureInfo.size.width * devicePixelRatio / scale).round(); + final int scaledWidth = (pictureInfo.size.width * devicePixelRatio / scale) + .round(); final int scaledHeight = (pictureInfo.size.height * devicePixelRatio / scale).round(); final RasterKey key = RasterKey(assetKey, scaledWidth, scaledHeight); diff --git a/packages/vector_graphics/lib/src/vector_graphics.dart b/packages/vector_graphics/lib/src/vector_graphics.dart index ceaf39a4eab..c5ae25d7ce3 100644 --- a/packages/vector_graphics/lib/src/vector_graphics.dart +++ b/packages/vector_graphics/lib/src/vector_graphics.dart @@ -499,10 +499,9 @@ class _VectorGraphicWidgetState extends State { final TextDirection direction = Directionality.of(context); if (direction == TextDirection.rtl) { child = Transform( - transform: - Matrix4.identity() - ..translate(pictureInfo.size.width) - ..scale(-1.0, 1.0), + transform: Matrix4.identity() + ..translate(pictureInfo.size.width) + ..scale(-1.0, 1.0), child: child, ); } diff --git a/packages/vector_graphics/pubspec.yaml b/packages/vector_graphics/pubspec.yaml index 43ac469bd73..98bb911fdfa 100644 --- a/packages/vector_graphics/pubspec.yaml +++ b/packages/vector_graphics/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 1.1.19 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/vector_graphics/test/listener_test.dart b/packages/vector_graphics/test/listener_test.dart index 210779ea8eb..6204b5bb02c 100644 --- a/packages/vector_graphics/test/listener_test.dart +++ b/packages/vector_graphics/test/listener_test.dart @@ -51,8 +51,8 @@ void main() { loader: const AssetBytesLoader('test'), ); final ui.Image image = info.picture.toImageSync(15, 15); - final Uint32List imageBytes = - (await image.toByteData())!.buffer.asUint32List(); + final Uint32List imageBytes = (await image.toByteData())!.buffer + .asUint32List(); expect(imageBytes.first, 0xFF000000); expect(imageBytes.last, 0x00000000); }, skip: kIsWeb); @@ -66,8 +66,8 @@ void main() { loader: const AssetBytesLoader('test'), ); final ui.Image image = info.picture.toImageSync(15, 15); - final Uint32List imageBytes = - (await image.toByteData())!.buffer.asUint32List(); + final Uint32List imageBytes = (await image.toByteData())!.buffer + .asUint32List(); expect(imageBytes.first, 0xFF000000); expect(imageBytes.last, 0xFF000000); }, skip: kIsWeb); diff --git a/packages/vector_graphics/test/vector_graphics_test.dart b/packages/vector_graphics/test/vector_graphics_test.dart index 9cb3d628c6e..1590897775f 100644 --- a/packages/vector_graphics/test/vector_graphics_test.dart +++ b/packages/vector_graphics/test/vector_graphics_test.dart @@ -675,8 +675,11 @@ void main() { await tester.pumpAndSettle(); final Matrix4 matrix = Matrix4.identity(); - final RenderObject transformObject = - find.byType(Transform).evaluate().first.renderObject!; + final RenderObject transformObject = find + .byType(Transform) + .evaluate() + .first + .renderObject!; bool visited = false; transformObject.visitChildren((RenderObject child) { if (!visited) { @@ -702,16 +705,13 @@ void main() { loader: const ThrowingBytesLoader(), width: 100, height: 100, - errorBuilder: ( - BuildContext context, - Object error, - StackTrace stackTrace, - ) { - return const Directionality( - textDirection: TextDirection.ltr, - child: Text('Error is handled'), - ); - }, + errorBuilder: + (BuildContext context, Object error, StackTrace stackTrace) { + return const Directionality( + textDirection: TextDirection.ltr, + child: Text('Error is handled'), + ); + }, ), ); await tester.pumpAndSettle(); diff --git a/packages/vector_graphics_codec/CHANGELOG.md b/packages/vector_graphics_codec/CHANGELOG.md index 2d4cdd4190b..10288d74dbd 100644 --- a/packages/vector_graphics_codec/CHANGELOG.md +++ b/packages/vector_graphics_codec/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 1.1.13 diff --git a/packages/vector_graphics_codec/pubspec.yaml b/packages/vector_graphics_codec/pubspec.yaml index 9af3d8004e0..dafecf91582 100644 --- a/packages/vector_graphics_codec/pubspec.yaml +++ b/packages/vector_graphics_codec/pubspec.yaml @@ -5,7 +5,7 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 1.1.13 environment: - sdk: ^3.7.0 + sdk: ^3.8.0 dev_dependencies: flutter_test: diff --git a/packages/vector_graphics_compiler/CHANGELOG.md b/packages/vector_graphics_compiler/CHANGELOG.md index bc6e41f1dff..567a300b46c 100644 --- a/packages/vector_graphics_compiler/CHANGELOG.md +++ b/packages/vector_graphics_compiler/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. + ## 1.1.19 * Updates allowed version range of `xml` to include up to 6.6.1. diff --git a/packages/vector_graphics_compiler/bin/vector_graphics_compiler.dart b/packages/vector_graphics_compiler/bin/vector_graphics_compiler.dart index bb9187ad436..4820b8d4c79 100644 --- a/packages/vector_graphics_compiler/bin/vector_graphics_compiler.dart +++ b/packages/vector_graphics_compiler/bin/vector_graphics_compiler.dart @@ -13,106 +13,104 @@ import 'package:vector_graphics_compiler/vector_graphics_compiler.dart'; import 'util/isolate_processor.dart'; -final ArgParser argParser = - ArgParser() - ..addOption( - 'current-color', - help: - 'The value (in ARGB format or a named SVG color) of the ' - '"currentColor" attribute.', - valueHelp: '0xFF000000', - defaultsTo: '0xFF000000', - ) - ..addOption( - 'font-size', - help: 'The basis for font size based values (i.e. em, ex).', - valueHelp: '14', - defaultsTo: '14', - ) - ..addOption( - 'x-height', - help: - 'The x-height or corpus size of the font. If unspecified, defaults ' - 'to half of font-size.', - valueHelp: '7', - ) - ..addOption( - 'libtessellator', - help: 'The path to a libtessellator dynamic library', - valueHelp: 'path/to/libtessellator.dylib', - hide: true, - ) - ..addOption( - 'libpathops', - help: 'The path to a libpathops dynamic library', - valueHelp: 'path/to/libpath_ops.dylib', - hide: true, - ) - ..addFlag( - 'tessellate', - help: - 'Convert path fills into a tessellated shape. This will improve ' - 'raster times at the cost of slightly larger file sizes.', - ) - ..addFlag( - 'optimize-masks', - help: 'Allows for masking optimizer to be enabled or disabled', - defaultsTo: true, - ) - ..addFlag( - 'optimize-clips', - help: 'Allows for clipping optimizer to be enabled or disabled', - defaultsTo: true, - ) - ..addFlag( - 'optimize-overdraw', - help: 'Allows for overdraw optimizer to be enabled or disabled', - defaultsTo: true, - ) - ..addOption( - 'input-dir', - help: - 'The path to a directory containing one or more SVGs. ' - 'Only includes files that end with .svg. ' - 'Cannot be combined with --input or --output.', - ) - ..addOption( - 'out-dir', - help: - 'The output directory path ' - 'use it with --input-dir to specific the output dirictory', - ) - ..addOption( - 'input', - abbr: 'i', - help: 'The path to a file containing a single SVG', - ) - ..addOption( - 'concurrency', - abbr: 'k', - help: - 'The maximum number of SVG processing isolates to spawn at once. ' - 'If not provided, defaults to the number of cores.', - ) - ..addFlag( - 'dump-debug', - help: - 'Dump a human readable debugging format alongside the compiled asset', - hide: true, - ) - ..addOption( - 'output', - abbr: 'o', - help: - 'The path to a file where the resulting vector_graphic will be written.\n' - 'If not provided, defaults to .vec', - ) - ..addFlag( - 'use-half-precision-control-points', - help: - 'Convert path control points into IEEE 754-2008 half precision floating point values.\n' - 'This reduces file size at the cost of lost precision at larger values.', - ); +final ArgParser argParser = ArgParser() + ..addOption( + 'current-color', + help: + 'The value (in ARGB format or a named SVG color) of the ' + '"currentColor" attribute.', + valueHelp: '0xFF000000', + defaultsTo: '0xFF000000', + ) + ..addOption( + 'font-size', + help: 'The basis for font size based values (i.e. em, ex).', + valueHelp: '14', + defaultsTo: '14', + ) + ..addOption( + 'x-height', + help: + 'The x-height or corpus size of the font. If unspecified, defaults ' + 'to half of font-size.', + valueHelp: '7', + ) + ..addOption( + 'libtessellator', + help: 'The path to a libtessellator dynamic library', + valueHelp: 'path/to/libtessellator.dylib', + hide: true, + ) + ..addOption( + 'libpathops', + help: 'The path to a libpathops dynamic library', + valueHelp: 'path/to/libpath_ops.dylib', + hide: true, + ) + ..addFlag( + 'tessellate', + help: + 'Convert path fills into a tessellated shape. This will improve ' + 'raster times at the cost of slightly larger file sizes.', + ) + ..addFlag( + 'optimize-masks', + help: 'Allows for masking optimizer to be enabled or disabled', + defaultsTo: true, + ) + ..addFlag( + 'optimize-clips', + help: 'Allows for clipping optimizer to be enabled or disabled', + defaultsTo: true, + ) + ..addFlag( + 'optimize-overdraw', + help: 'Allows for overdraw optimizer to be enabled or disabled', + defaultsTo: true, + ) + ..addOption( + 'input-dir', + help: + 'The path to a directory containing one or more SVGs. ' + 'Only includes files that end with .svg. ' + 'Cannot be combined with --input or --output.', + ) + ..addOption( + 'out-dir', + help: + 'The output directory path ' + 'use it with --input-dir to specific the output dirictory', + ) + ..addOption( + 'input', + abbr: 'i', + help: 'The path to a file containing a single SVG', + ) + ..addOption( + 'concurrency', + abbr: 'k', + help: + 'The maximum number of SVG processing isolates to spawn at once. ' + 'If not provided, defaults to the number of cores.', + ) + ..addFlag( + 'dump-debug', + help: 'Dump a human readable debugging format alongside the compiled asset', + hide: true, + ) + ..addOption( + 'output', + abbr: 'o', + help: + 'The path to a file where the resulting vector_graphic will be written.\n' + 'If not provided, defaults to .vec', + ) + ..addFlag( + 'use-half-precision-control-points', + help: + 'Convert path control points into IEEE 754-2008 half precision floating point values.\n' + 'This reduces file size at the cost of lost precision at larger values.', + ); void validateOptions(ArgResults results) { if (results.wasParsed('input-dir') && @@ -137,10 +135,9 @@ SvgTheme _parseTheme(ArgResults results) { return SvgTheme( currentColor: currentColor, fontSize: double.tryParse(results['font-size'] as String) ?? 14, - xHeight: - results.wasParsed('x-height') - ? double.tryParse(results['x-height'] as String) - : null, + xHeight: results.wasParsed('x-height') + ? double.tryParse(results['x-height'] as String) + : null, ); } diff --git a/packages/vector_graphics_compiler/lib/src/debug_format.dart b/packages/vector_graphics_compiler/lib/src/debug_format.dart index 2de6d032aa6..2ca0cf63da0 100644 --- a/packages/vector_graphics_compiler/lib/src/debug_format.dart +++ b/packages/vector_graphics_compiler/lib/src/debug_format.dart @@ -54,8 +54,9 @@ class _DebugVectorGraphicsListener extends VectorGraphicsCodecListener { @override void onDrawPath(int pathId, int? paintId, int? patternId) { - final String patternContext = - patternId != null ? ', patternId:$patternId' : ''; + final String patternContext = patternId != null + ? ', patternId:$patternId' + : ''; buffer.writeln('DrawPath: id:$pathId (paintId:$paintId$patternContext)'); } diff --git a/packages/vector_graphics_compiler/lib/src/geometry/matrix.dart b/packages/vector_graphics_compiler/lib/src/geometry/matrix.dart index 54c1f7bf234..200bd59d4c5 100644 --- a/packages/vector_graphics_compiler/lib/src/geometry/matrix.dart +++ b/packages/vector_graphics_compiler/lib/src/geometry/matrix.dart @@ -198,7 +198,8 @@ class AffineMatrix { } @override - String toString() => ''' + String toString() => + ''' [ $a, $c, $e ] [ $b, $d, $f ] [ 0.0, 0.0, 1.0 ] // _m4_10 = $_m4_10 diff --git a/packages/vector_graphics_compiler/lib/src/svg/node.dart b/packages/vector_graphics_compiler/lib/src/svg/node.dart index 1475c3efd99..3a03413790b 100644 --- a/packages/vector_graphics_compiler/lib/src/svg/node.dart +++ b/packages/vector_graphics_compiler/lib/src/svg/node.dart @@ -260,19 +260,17 @@ class TextPositionNode extends ParentNode { (computedTransform.encodableInRect && (hasXY || hasDxDy)); if (hasXY) { - final Point baseline = - consumeTransform - ? computedTransform.transformPoint(Point(x, y)) - : Point(x, y); + final Point baseline = consumeTransform + ? computedTransform.transformPoint(Point(x, y)) + : Point(x, y); x = baseline.x; y = baseline.y; } if (hasDxDy) { - final Point baseline = - consumeTransform - ? computedTransform.transformPoint(Point(dx, dy)) - : Point(dx, dy); + final Point baseline = consumeTransform + ? computedTransform.transformPoint(Point(dx, dy)) + : Point(dx, dy); dx = baseline.x; dy = baseline.y; } @@ -537,13 +535,9 @@ class TextNode extends AttributedNode { SvgAttributes newAttributes, { bool replace = false, }) { - final SvgAttributes resolvedAttributes = - replace - ? newAttributes.applyParent( - attributes, - transformOverride: transform, - ) - : attributes.applyParent(newAttributes); + final SvgAttributes resolvedAttributes = replace + ? newAttributes.applyParent(attributes, transformOverride: transform) + : attributes.applyParent(newAttributes); return TextNode(text, resolvedAttributes); } diff --git a/packages/vector_graphics_compiler/lib/src/svg/numbers.dart b/packages/vector_graphics_compiler/lib/src/svg/numbers.dart index a13bb3e2f22..f58cbae0800 100644 --- a/packages/vector_graphics_compiler/lib/src/svg/numbers.dart +++ b/packages/vector_graphics_compiler/lib/src/svg/numbers.dart @@ -18,14 +18,13 @@ double? parseDouble(String? rawDouble, {bool tryParse = false}) { return null; } - rawDouble = - rawDouble - .replaceFirst('rem', '') - .replaceFirst('em', '') - .replaceFirst('ex', '') - .replaceFirst('px', '') - .replaceFirst('pt', '') - .trim(); + rawDouble = rawDouble + .replaceFirst('rem', '') + .replaceFirst('em', '') + .replaceFirst('ex', '') + .replaceFirst('px', '') + .replaceFirst('pt', '') + .trim(); if (tryParse) { return double.tryParse(rawDouble); diff --git a/packages/vector_graphics_compiler/lib/src/svg/parser.dart b/packages/vector_graphics_compiler/lib/src/svg/parser.dart index de66f928678..3ff4a2398dc 100644 --- a/packages/vector_graphics_compiler/lib/src/svg/parser.dart +++ b/packages/vector_graphics_compiler/lib/src/svg/parser.dart @@ -211,18 +211,17 @@ class _Elements { return; } - final AffineMatrix transform = (parseTransform( - parserState.attribute('transform'), - ) ?? - AffineMatrix.identity) - .translated( - parserState.parseDoubleWithUnits( - parserState.attribute('x', def: '0'), - )!, - parserState.parseDoubleWithUnits( - parserState.attribute('y', def: '0'), - )!, - ); + final AffineMatrix transform = + (parseTransform(parserState.attribute('transform')) ?? + AffineMatrix.identity) + .translated( + parserState.parseDoubleWithUnits( + parserState.attribute('x', def: '0'), + )!, + parserState.parseDoubleWithUnits( + parserState.attribute('y', def: '0'), + )!, + ); final ParentNode group = ParentNode( // parserState._currentAttributes, @@ -265,8 +264,10 @@ class _Elements { continue; } if (event is XmlStartElementEvent) { - final String rawOpacity = - parserState.attribute('stop-opacity', def: '1')!; + final String rawOpacity = parserState.attribute( + 'stop-opacity', + def: '1', + )!; final Color stopColor = parserState.parseColor( parserState.attribute('stop-color'), @@ -442,11 +443,10 @@ class _Elements { }; final int semiColonLocation = xlinkHref.indexOf(';') + 1; final int commaLocation = xlinkHref.indexOf(',', semiColonLocation) + 1; - final String mimeType = - xlinkHref - .substring(xlinkHref.indexOf('/') + 1, semiColonLocation - 1) - .replaceAll(_whitespacePattern, '') - .toLowerCase(); + final String mimeType = xlinkHref + .substring(xlinkHref.indexOf('/') + 1, semiColonLocation - 1) + .replaceAll(_whitespacePattern, '') + .toLowerCase(); final ImageFormat? format = supportedMimeTypes[mimeType]; if (format == null) { @@ -487,16 +487,15 @@ class _Elements { // ignore: avoid_classes_with_only_static_members class _Paths { static Path circle(SvgParser parserState) { - final double cx = - parserState.parseDoubleWithUnits( - parserState.attribute('cx', def: '0'), - )!; - final double cy = - parserState.parseDoubleWithUnits( - parserState.attribute('cy', def: '0'), - )!; - final double r = - parserState.parseDoubleWithUnits(parserState.attribute('r', def: '0'))!; + final double cx = parserState.parseDoubleWithUnits( + parserState.attribute('cx', def: '0'), + )!; + final double cy = parserState.parseDoubleWithUnits( + parserState.attribute('cy', def: '0'), + )!; + final double r = parserState.parseDoubleWithUnits( + parserState.attribute('r', def: '0'), + )!; final Rect oval = Rect.fromCircle(cx, cy, r); return PathBuilder( parserState._currentAttributes.fillRule, @@ -509,18 +508,18 @@ class _Paths { } static Path rect(SvgParser parserState) { - final double x = - parserState.parseDoubleWithUnits(parserState.attribute('x', def: '0'))!; - final double y = - parserState.parseDoubleWithUnits(parserState.attribute('y', def: '0'))!; - final double w = - parserState.parseDoubleWithUnits( - parserState.attribute('width', def: '0'), - )!; - final double h = - parserState.parseDoubleWithUnits( - parserState.attribute('height', def: '0'), - )!; + final double x = parserState.parseDoubleWithUnits( + parserState.attribute('x', def: '0'), + )!; + final double y = parserState.parseDoubleWithUnits( + parserState.attribute('y', def: '0'), + )!; + final double w = parserState.parseDoubleWithUnits( + parserState.attribute('width', def: '0'), + )!; + final double h = parserState.parseDoubleWithUnits( + parserState.attribute('height', def: '0'), + )!; String? rxRaw = parserState.attribute('rx'); String? ryRaw = parserState.attribute('ry'); rxRaw ??= ryRaw; @@ -558,22 +557,18 @@ class _Paths { } static Path ellipse(SvgParser parserState) { - final double cx = - parserState.parseDoubleWithUnits( - parserState.attribute('cx', def: '0'), - )!; - final double cy = - parserState.parseDoubleWithUnits( - parserState.attribute('cy', def: '0'), - )!; - final double rx = - parserState.parseDoubleWithUnits( - parserState.attribute('rx', def: '0'), - )!; - final double ry = - parserState.parseDoubleWithUnits( - parserState.attribute('ry', def: '0'), - )!; + final double cx = parserState.parseDoubleWithUnits( + parserState.attribute('cx', def: '0'), + )!; + final double cy = parserState.parseDoubleWithUnits( + parserState.attribute('cy', def: '0'), + )!; + final double rx = parserState.parseDoubleWithUnits( + parserState.attribute('rx', def: '0'), + )!; + final double ry = parserState.parseDoubleWithUnits( + parserState.attribute('ry', def: '0'), + )!; final Rect r = Rect.fromLTWH(cx - rx, cy - ry, rx * 2, ry * 2); return PathBuilder( @@ -582,22 +577,18 @@ class _Paths { } static Path line(SvgParser parserState) { - final double x1 = - parserState.parseDoubleWithUnits( - parserState.attribute('x1', def: '0'), - )!; - final double x2 = - parserState.parseDoubleWithUnits( - parserState.attribute('x2', def: '0'), - )!; - final double y1 = - parserState.parseDoubleWithUnits( - parserState.attribute('y1', def: '0'), - )!; - final double y2 = - parserState.parseDoubleWithUnits( - parserState.attribute('y2', def: '0'), - )!; + final double x1 = parserState.parseDoubleWithUnits( + parserState.attribute('x1', def: '0'), + )!; + final double x2 = parserState.parseDoubleWithUnits( + parserState.attribute('x2', def: '0'), + )!; + final double y1 = parserState.parseDoubleWithUnits( + parserState.attribute('y1', def: '0'), + )!; + final double y2 = parserState.parseDoubleWithUnits( + parserState.attribute('y2', def: '0'), + )!; return PathBuilder( parserState._currentAttributes.fillRule, @@ -1379,53 +1370,49 @@ class SvgParser { if (colorString.length == 7 || colorString.length == 9) { final int color = int.parse(colorString.substring(1, 7), radix: 16); - final int alpha = - colorString.length == 9 - ? int.parse(colorString.substring(7, 9), radix: 16) - : 255; + final int alpha = colorString.length == 9 + ? int.parse(colorString.substring(7, 9), radix: 16) + : 255; return Color(color | alpha << 24); } } // handle rgba() colors e.g. rgba(255, 255, 255, 1.0) if (colorString.toLowerCase().startsWith('rgba')) { - final List rawColorElements = - colorString - .substring(colorString.indexOf('(') + 1, colorString.indexOf(')')) - .split(',') - .map((String rawColor) => rawColor.trim()) - .toList(); + final List rawColorElements = colorString + .substring(colorString.indexOf('(') + 1, colorString.indexOf(')')) + .split(',') + .map((String rawColor) => rawColor.trim()) + .toList(); final double opacity = parseDouble(rawColorElements.removeLast())!; - final List rgb = - rawColorElements - .map((String rawColor) => int.parse(rawColor)) - .toList(); + final List rgb = rawColorElements + .map((String rawColor) => int.parse(rawColor)) + .toList(); return Color.fromRGBO(rgb[0], rgb[1], rgb[2], opacity); } // Conversion code from: https://github.com/MichaelFenwick/Color, thanks :) if (colorString.toLowerCase().startsWith('hsl')) { - final List values = - colorString - .substring(colorString.indexOf('(') + 1, colorString.indexOf(')')) - .split(',') - .map((String rawColor) { - rawColor = rawColor.trim(); - - if (rawColor.endsWith('%')) { - rawColor = rawColor.substring(0, rawColor.length - 1); - } - - if (rawColor.contains('.')) { - return (parseDouble(rawColor)! * 2.55).round(); - } - - return int.parse(rawColor); - }) - .toList(); + final List values = colorString + .substring(colorString.indexOf('(') + 1, colorString.indexOf(')')) + .split(',') + .map((String rawColor) { + rawColor = rawColor.trim(); + + if (rawColor.endsWith('%')) { + rawColor = rawColor.substring(0, rawColor.length - 1); + } + + if (rawColor.contains('.')) { + return (parseDouble(rawColor)! * 2.55).round(); + } + + return int.parse(rawColor); + }) + .toList(); final double hue = values[0] / 360 % 1; final double saturation = values[1] / 100; final double luminance = values[2] / 100; @@ -1452,18 +1439,16 @@ class SvgParser { rgb[2] = 6 - hue * 6; } - rgb = - rgb - .map((double val) => val + (1 - saturation) * (0.5 - val)) - .toList(); + rgb = rgb + .map((double val) => val + (1 - saturation) * (0.5 - val)) + .toList(); if (luminance < 0.5) { rgb = rgb.map((double val) => luminance * 2 * val).toList(); } else { - rgb = - rgb - .map((double val) => luminance * 2 * (1 - val) + 2 * val - 1) - .toList(); + rgb = rgb + .map((double val) => luminance * 2 * (1 - val) + 2 * val - 1) + .toList(); } rgb = rgb.map((double val) => val * 255).toList(); @@ -1478,19 +1463,18 @@ class SvgParser { // handle rgb() colors e.g. rgb(255, 255, 255) if (colorString.toLowerCase().startsWith('rgb')) { - final List rgb = - colorString - .substring(colorString.indexOf('(') + 1, colorString.indexOf(')')) - .split(',') - .map((String rawColor) { - rawColor = rawColor.trim(); - if (rawColor.endsWith('%')) { - rawColor = rawColor.substring(0, rawColor.length - 1); - return (parseDouble(rawColor)! * 2.55).round(); - } - return int.parse(rawColor); - }) - .toList(); + final List rgb = colorString + .substring(colorString.indexOf('(') + 1, colorString.indexOf(')')) + .split(',') + .map((String rawColor) { + rawColor = rawColor.trim(); + if (rawColor.endsWith('%')) { + rawColor = rawColor.substring(0, rawColor.length - 1); + return (parseDouble(rawColor)! * 2.55).round(); + } + return int.parse(rawColor); + }) + .toList(); // rgba() isn't really in the spec, but Firefox supported it at one point so why not. final int a = rgb.length > 3 ? rgb[3] : 255; @@ -1593,10 +1577,9 @@ class SvgParser { return SvgStrokeAttributes._( _definitions, shaderId: shaderId, - color: - rawStroke == 'none' - ? const ColorOrNone.none() - : ColorOrNone.color(color), + color: rawStroke == 'none' + ? const ColorOrNone.none() + : ColorOrNone.color(color), cap: _parseCap(rawStrokeCap, null), join: _parseJoin(rawLineJoin, null), miterLimit: parseDouble(rawMiterLimit), @@ -1651,10 +1634,9 @@ class SvgParser { return SvgFillAttributes._( _definitions, - color: - rawFill == 'none' - ? const ColorOrNone.none() - : ColorOrNone.color(fillColor), + color: rawFill == 'none' + ? const ColorOrNone.none() + : ColorOrNone.color(fillColor), opacity: opacity, ); } @@ -1690,10 +1672,9 @@ class SvgParser { dx: DoubleOrPercentage.fromString(rawDx), dy: DoubleOrPercentage.fromString(rawDy), href: attributeMap['href'], - color: - attributeMap['color']?.toLowerCase() == 'none' - ? const ColorOrNone.none() - : ColorOrNone.color(color), + color: attributeMap['color']?.toLowerCase() == 'none' + ? const ColorOrNone.none() + : ColorOrNone.color(color), stroke: _parseStrokeAttributes(attributeMap, opacity, color, id), fill: _parseFillAttributes(attributeMap, opacity, color, id), fillRule: parseRawFillRule(attributeMap['fill-rule']), diff --git a/packages/vector_graphics_compiler/lib/src/svg/parsers.dart b/packages/vector_graphics_compiler/lib/src/svg/parsers.dart index 2e69faee550..fec2eb89c7e 100644 --- a/packages/vector_graphics_compiler/lib/src/svg/parsers.dart +++ b/packages/vector_graphics_compiler/lib/src/svg/parsers.dart @@ -66,8 +66,10 @@ AffineMatrix? parseTransform(String? transform) { if (!_transformValidator.hasMatch(transform)) { throw StateError('illegal or unsupported transform: $transform'); } - final Iterable matches = - _transformCommand.allMatches(transform).toList().reversed; + final Iterable matches = _transformCommand + .allMatches(transform) + .toList() + .reversed; AffineMatrix result = AffineMatrix.identity; for (final Match m in matches) { final String command = m.group(1)!.trim(); diff --git a/packages/vector_graphics_compiler/pubspec.yaml b/packages/vector_graphics_compiler/pubspec.yaml index 93cec9edd7f..9e746432005 100644 --- a/packages/vector_graphics_compiler/pubspec.yaml +++ b/packages/vector_graphics_compiler/pubspec.yaml @@ -8,7 +8,7 @@ executables: vector_graphics_compiler: environment: - sdk: ^3.7.0 + sdk: ^3.8.0 dependencies: args: ^2.3.0 diff --git a/packages/vector_graphics_compiler/test/cli_test.dart b/packages/vector_graphics_compiler/test/cli_test.dart index 1a5121f0e44..ea949906588 100644 --- a/packages/vector_graphics_compiler/test/cli_test.dart +++ b/packages/vector_graphics_compiler/test/cli_test.dart @@ -105,24 +105,22 @@ void main() { final Directory outDir = Directory(outTestDir); if (inputDir.existsSync() && outDir.existsSync()) { - final List inputTestFiles = - inputDir - .listSync(recursive: true) - .whereType() - .where((File element) => element.path.endsWith('svg')) - .map((File e) => p.basenameWithoutExtension(e.path)) - .toList(); - - final List outTestFiles = - outDir - .listSync(recursive: true) - .whereType() - .where((File element) => element.path.endsWith('vec')) - .map( - (File e) => - p.withoutExtension(p.basenameWithoutExtension(e.path)), - ) - .toList(); + final List inputTestFiles = inputDir + .listSync(recursive: true) + .whereType() + .where((File element) => element.path.endsWith('svg')) + .map((File e) => p.basenameWithoutExtension(e.path)) + .toList(); + + final List outTestFiles = outDir + .listSync(recursive: true) + .whereType() + .where((File element) => element.path.endsWith('vec')) + .map( + (File e) => + p.withoutExtension(p.basenameWithoutExtension(e.path)), + ) + .toList(); if (listEquals(inputTestFiles, outTestFiles)) { passed = true; diff --git a/packages/vector_graphics_compiler/test/end_to_end_test.dart b/packages/vector_graphics_compiler/test/end_to_end_test.dart index 2f5f37d6eee..490bf573e20 100644 --- a/packages/vector_graphics_compiler/test/end_to_end_test.dart +++ b/packages/vector_graphics_compiler/test/end_to_end_test.dart @@ -270,7 +270,8 @@ void main() { }); test('Encodes image elids trivial translation transform', () async { - const String svg = ''' + const String svg = + ''' @@ -299,7 +300,8 @@ void main() { }); test('Encodes image elids trivial scale transform', () async { - const String svg = ''' + const String svg = + ''' @@ -328,7 +330,8 @@ void main() { }); test('Encodes image does not elide non-trivial transform', () async { - const String svg = ''' + const String svg = + ''' diff --git a/packages/vector_graphics_compiler/test/masking_optimizer_test.dart b/packages/vector_graphics_compiler/test/masking_optimizer_test.dart index 79a1f413e69..9280d0c701e 100644 --- a/packages/vector_graphics_compiler/test/masking_optimizer_test.dart +++ b/packages/vector_graphics_compiler/test/masking_optimizer_test.dart @@ -226,7 +226,9 @@ void main() { blendMode: BlendMode.multiply, fill: Fill(color: Color(0x98ffffff), shader: gradient1), ), - Paint(fill: Fill(color: Color(0x98ffffff), shader: gradient2)), + Paint( + fill: Fill(color: Color(0x98ffffff), shader: gradient2), + ), ]); expect(instructions.commands, const [ diff --git a/packages/vector_graphics_compiler/test/overdraw_optimizer_test.dart b/packages/vector_graphics_compiler/test/overdraw_optimizer_test.dart index 75506a610dd..87c521d4505 100644 --- a/packages/vector_graphics_compiler/test/overdraw_optimizer_test.dart +++ b/packages/vector_graphics_compiler/test/overdraw_optimizer_test.dart @@ -93,8 +93,14 @@ void main() { expect(pathNodesOld.length, pathNodesNew.length); expect(instructions.paints, const [ - Paint(blendMode: BlendMode.srcOver, fill: Fill(color: Color(0xffff0000))), - Paint(blendMode: BlendMode.srcOver, fill: Fill(color: Color(0xff0000ff))), + Paint( + blendMode: BlendMode.srcOver, + fill: Fill(color: Color(0xffff0000)), + ), + Paint( + blendMode: BlendMode.srcOver, + fill: Fill(color: Color(0xff0000ff)), + ), ]); expect(instructions.paths, [ @@ -141,9 +147,18 @@ void main() { expect(pathNodesNew.length, 3); expect(instructions.paints, const [ - Paint(blendMode: BlendMode.srcOver, fill: Fill(color: Color(0x7fff0000))), - Paint(blendMode: BlendMode.srcOver, fill: Fill(color: Color(0x4c0000ff))), - Paint(blendMode: BlendMode.srcOver, fill: Fill(color: Color(0xa58a0075))), + Paint( + blendMode: BlendMode.srcOver, + fill: Fill(color: Color(0x7fff0000)), + ), + Paint( + blendMode: BlendMode.srcOver, + fill: Fill(color: Color(0x4c0000ff)), + ), + Paint( + blendMode: BlendMode.srcOver, + fill: Fill(color: Color(0xa58a0075)), + ), ]); expect(instructions.paths, [ @@ -208,8 +223,14 @@ void main() { expect(pathNodesNew.length, 2); expect(instructions.paints, const [ - Paint(blendMode: BlendMode.srcOver, fill: Fill(color: Color(0x7fff0000))), - Paint(blendMode: BlendMode.srcOver, fill: Fill(color: Color(0xff0000ff))), + Paint( + blendMode: BlendMode.srcOver, + fill: Fill(color: Color(0x7fff0000)), + ), + Paint( + blendMode: BlendMode.srcOver, + fill: Fill(color: Color(0xff0000ff)), + ), ]); expect(instructions.paths, [ @@ -256,9 +277,18 @@ void main() { expect(pathNodesNew.length, 3); expect(instructions.paints, const [ - Paint(blendMode: BlendMode.srcOver, fill: Fill(color: Color(0xffff0000))), - Paint(blendMode: BlendMode.srcOver, fill: Fill(color: Color(0x7f0000ff))), - Paint(blendMode: BlendMode.srcOver, fill: Fill(color: Color(0xff80007f))), + Paint( + blendMode: BlendMode.srcOver, + fill: Fill(color: Color(0xffff0000)), + ), + Paint( + blendMode: BlendMode.srcOver, + fill: Fill(color: Color(0x7f0000ff)), + ), + Paint( + blendMode: BlendMode.srcOver, + fill: Fill(color: Color(0xff80007f)), + ), ]); expect(instructions.paths, [ @@ -345,19 +375,58 @@ void main() { expect(pathNodesNew.length, 22); expect(instructions.paints, const [ - Paint(blendMode: BlendMode.srcOver, fill: Fill(color: Color(0xff0000ff))), - Paint(blendMode: BlendMode.srcOver, fill: Fill(color: Color(0xffff0000))), - Paint(blendMode: BlendMode.srcOver, fill: Fill(color: Color(0xccff0000))), - Paint(blendMode: BlendMode.srcOver, fill: Fill(color: Color(0x99ff0000))), - Paint(blendMode: BlendMode.srcOver, fill: Fill(color: Color(0x66ff0000))), - Paint(blendMode: BlendMode.srcOver, fill: Fill(color: Color(0x33ff0000))), - Paint(blendMode: BlendMode.srcOver, fill: Fill(color: Color(0xff008000))), - Paint(blendMode: BlendMode.srcOver, fill: Fill(color: Color(0xbfff0000))), - Paint(blendMode: BlendMode.srcOver, fill: Fill(color: Color(0xbf008000))), - Paint(blendMode: BlendMode.srcOver, fill: Fill(color: Color(0x7fff0000))), - Paint(blendMode: BlendMode.srcOver, fill: Fill(color: Color(0x7f008000))), - Paint(blendMode: BlendMode.srcOver, fill: Fill(color: Color(0x3fff0000))), - Paint(blendMode: BlendMode.srcOver, fill: Fill(color: Color(0x3f008000))), + Paint( + blendMode: BlendMode.srcOver, + fill: Fill(color: Color(0xff0000ff)), + ), + Paint( + blendMode: BlendMode.srcOver, + fill: Fill(color: Color(0xffff0000)), + ), + Paint( + blendMode: BlendMode.srcOver, + fill: Fill(color: Color(0xccff0000)), + ), + Paint( + blendMode: BlendMode.srcOver, + fill: Fill(color: Color(0x99ff0000)), + ), + Paint( + blendMode: BlendMode.srcOver, + fill: Fill(color: Color(0x66ff0000)), + ), + Paint( + blendMode: BlendMode.srcOver, + fill: Fill(color: Color(0x33ff0000)), + ), + Paint( + blendMode: BlendMode.srcOver, + fill: Fill(color: Color(0xff008000)), + ), + Paint( + blendMode: BlendMode.srcOver, + fill: Fill(color: Color(0xbfff0000)), + ), + Paint( + blendMode: BlendMode.srcOver, + fill: Fill(color: Color(0xbf008000)), + ), + Paint( + blendMode: BlendMode.srcOver, + fill: Fill(color: Color(0x7fff0000)), + ), + Paint( + blendMode: BlendMode.srcOver, + fill: Fill(color: Color(0x7f008000)), + ), + Paint( + blendMode: BlendMode.srcOver, + fill: Fill(color: Color(0x3fff0000)), + ), + Paint( + blendMode: BlendMode.srcOver, + fill: Fill(color: Color(0x3f008000)), + ), ]); expect(instructions.paths, [ diff --git a/packages/vector_graphics_compiler/test/parser_test.dart b/packages/vector_graphics_compiler/test/parser_test.dart index 2d1bca60adf..14369bebe75 100644 --- a/packages/vector_graphics_compiler/test/parser_test.dart +++ b/packages/vector_graphics_compiler/test/parser_test.dart @@ -212,8 +212,14 @@ void main() { final VectorInstructions instructions = parseWithoutOptimizers(svg); // Should _not_ contain a paint with an opaque black fill for the rect with class "frame-background". expect(instructions.paints, const [ - Paint(blendMode: BlendMode.srcOver, fill: Fill(color: Color(0xff22c55e))), - Paint(blendMode: BlendMode.srcOver, fill: Fill(color: Color(0xfff59e0b))), + Paint( + blendMode: BlendMode.srcOver, + fill: Fill(color: Color(0xff22c55e)), + ), + Paint( + blendMode: BlendMode.srcOver, + fill: Fill(color: Color(0xfff59e0b)), + ), ]); }); @@ -433,12 +439,21 @@ void main() { '''); expect(instructions.paints, const [ - Paint(blendMode: BlendMode.srcOver, fill: Fill(color: Color(0x06202124))), + Paint( + blendMode: BlendMode.srcOver, + fill: Fill(color: Color(0x06202124)), + ), // The paint for the saveLayer. - Paint(blendMode: BlendMode.srcOver, fill: Fill(color: Color(0x0a000000))), + Paint( + blendMode: BlendMode.srcOver, + fill: Fill(color: Color(0x0a000000)), + ), // The paint for the path drawn in the saveLayer - must not be the same as // the saveLayer otherwise the path will be drawn almost completely transparent. - Paint(blendMode: BlendMode.srcOver, fill: Fill(color: Color.opaqueBlack)), + Paint( + blendMode: BlendMode.srcOver, + fill: Fill(color: Color.opaqueBlack), + ), ]); expect(instructions.commands, const [ DrawCommand(DrawCommandType.path, objectId: 0, paintId: 0), @@ -1107,8 +1122,14 @@ void main() { final VectorInstructions instructions = parseWithoutOptimizers(svg); expect(instructions.paints, const [ Paint(fill: Fill(color: Color(0xffff0000))), - Paint(blendMode: BlendMode.screen, fill: Fill(color: Color.opaqueBlack)), - Paint(blendMode: BlendMode.screen, fill: Fill(color: Color(0xff008000))), + Paint( + blendMode: BlendMode.screen, + fill: Fill(color: Color.opaqueBlack), + ), + Paint( + blendMode: BlendMode.screen, + fill: Fill(color: Color(0xff008000)), + ), ]); expect(instructions.commands, const [ DrawCommand(DrawCommandType.path, objectId: 0, paintId: 0), diff --git a/packages/vector_graphics_compiler/test/path_ops_test.dart b/packages/vector_graphics_compiler/test/path_ops_test.dart index e8c95f5242e..ea480809083 100644 --- a/packages/vector_graphics_compiler/test/path_ops_test.dart +++ b/packages/vector_graphics_compiler/test/path_ops_test.dart @@ -14,13 +14,12 @@ void main() { } }); test('Path tests', () { - final Path path = - Path() - ..lineTo(10, 0) - ..lineTo(10, 10) - ..lineTo(0, 10) - ..close() - ..cubicTo(30, 30, 40, 40, 50, 50); + final Path path = Path() + ..lineTo(10, 0) + ..lineTo(10, 10) + ..lineTo(0, 10) + ..close() + ..cubicTo(30, 30, 40, 40, 50, 50); expect(path.fillType, FillType.nonZero); expect(path.verbs.toList(), [ @@ -61,20 +60,18 @@ void main() { }); test('Ops test', () { - final Path cubics = - Path() - ..moveTo(16, 128) - ..cubicTo(16, 66, 66, 16, 128, 16) - ..cubicTo(240, 66, 16, 66, 240, 128) - ..close(); + final Path cubics = Path() + ..moveTo(16, 128) + ..cubicTo(16, 66, 66, 16, 128, 16) + ..cubicTo(240, 66, 16, 66, 240, 128) + ..close(); - final Path quad = - Path() - ..moveTo(55, 16) - ..lineTo(200, 80) - ..lineTo(198, 230) - ..lineTo(15, 230) - ..close(); + final Path quad = Path() + ..moveTo(55, 16) + ..lineTo(200, 80) + ..lineTo(198, 230) + ..lineTo(15, 230) + ..close(); final Path intersection = cubics.applyOp(quad, PathOp.intersect); @@ -109,135 +106,105 @@ void main() { }); test('Quad', () { - final Path top = - Path() - ..moveTo(87.998, 103.591) - ..lineTo(82.72, 103.591) - ..lineTo(82.72, 106.64999999999999) - ..lineTo(87.998, 106.64999999999999) - ..lineTo(87.998, 103.591) - ..close(); + final Path top = Path() + ..moveTo(87.998, 103.591) + ..lineTo(82.72, 103.591) + ..lineTo(82.72, 106.64999999999999) + ..lineTo(87.998, 106.64999999999999) + ..lineTo(87.998, 103.591) + ..close(); - final Path bottom = - Path() - ..moveTo(116.232, 154.452) - ..lineTo(19.031999999999996, 154.452) - ..cubicTo( - 18.671999999999997, - 142.112, - 21.361999999999995, - 132.59199999999998, - 26.101999999999997, - 125.372, - ) - ..cubicTo( - 32.552, - 115.55199999999999, - 42.782, - 110.012, - 54.30199999999999, - 107.502, - ) - ..cubicTo( - 56.931999185062395, - 106.9278703703336, - 59.593157782987156, - 106.50716022812718, - 62.27200212186002, - 106.24200362009655, - ) - ..lineTo(62.291999999999994, 106.24199999999999) - ..cubicTo( - 67.10118331429277, - 105.77278829340533, - 71.940772522921, - 105.69920780785604, - 76.76199850891219, - 106.021997940542, - ) - ..cubicTo( - 78.762, - 106.142, - 80.749, - 106.32199999999999, - 82.722, - 106.562, - ) - ..lineTo(83.362, 106.652) - ..cubicTo( - 84.112, - 106.742, - 84.85199999999999, - 106.852, - 85.592, - 106.972, - ) - ..cubicTo( - 86.852, - 107.152, - 88.102, - 107.372, - 89.342, - 107.60199999999999, - ) - ..cubicTo( - 89.542, - 107.642, - 89.732, - 107.67199999999998, - 89.922, - 107.71199999999999, - ) - ..cubicTo( - 91.54899999999999, - 108.02599999999998, - 93.14, - 108.502, - 94.672, - 109.13199999999999, - ) - ..cubicTo( - 98.35184786478965, - 110.61003782601773, - 101.5939983878398, - 113.00207032444644, - 104.09199525642647, - 116.08199471003054, - ) - ..cubicTo( - 104.181, - 116.17999999999999, - 104.264, - 116.28399999999999, - 104.342, - 116.392, - ) - ..cubicTo(104.512, 116.612, 104.682, 116.832, 104.842, 117.062) - ..cubicTo( - 105.102, - 117.41199999999999, - 105.352, - 117.77199999999999, - 105.592, - 118.142, - ) - ..cubicTo( - 107.63018430068513, - 121.33505319707416, - 109.25008660688327, - 124.77650539945358, - 110.41200699229772, - 128.38200813032248, - ) - ..cubicTo( - 112.762, - 135.252, - 114.50200000000001, - 143.862, - 116.232, - 154.452, - ) - ..close(); + final Path bottom = Path() + ..moveTo(116.232, 154.452) + ..lineTo(19.031999999999996, 154.452) + ..cubicTo( + 18.671999999999997, + 142.112, + 21.361999999999995, + 132.59199999999998, + 26.101999999999997, + 125.372, + ) + ..cubicTo( + 32.552, + 115.55199999999999, + 42.782, + 110.012, + 54.30199999999999, + 107.502, + ) + ..cubicTo( + 56.931999185062395, + 106.9278703703336, + 59.593157782987156, + 106.50716022812718, + 62.27200212186002, + 106.24200362009655, + ) + ..lineTo(62.291999999999994, 106.24199999999999) + ..cubicTo( + 67.10118331429277, + 105.77278829340533, + 71.940772522921, + 105.69920780785604, + 76.76199850891219, + 106.021997940542, + ) + ..cubicTo(78.762, 106.142, 80.749, 106.32199999999999, 82.722, 106.562) + ..lineTo(83.362, 106.652) + ..cubicTo(84.112, 106.742, 84.85199999999999, 106.852, 85.592, 106.972) + ..cubicTo(86.852, 107.152, 88.102, 107.372, 89.342, 107.60199999999999) + ..cubicTo( + 89.542, + 107.642, + 89.732, + 107.67199999999998, + 89.922, + 107.71199999999999, + ) + ..cubicTo( + 91.54899999999999, + 108.02599999999998, + 93.14, + 108.502, + 94.672, + 109.13199999999999, + ) + ..cubicTo( + 98.35184786478965, + 110.61003782601773, + 101.5939983878398, + 113.00207032444644, + 104.09199525642647, + 116.08199471003054, + ) + ..cubicTo( + 104.181, + 116.17999999999999, + 104.264, + 116.28399999999999, + 104.342, + 116.392, + ) + ..cubicTo(104.512, 116.612, 104.682, 116.832, 104.842, 117.062) + ..cubicTo( + 105.102, + 117.41199999999999, + 105.352, + 117.77199999999999, + 105.592, + 118.142, + ) + ..cubicTo( + 107.63018430068513, + 121.33505319707416, + 109.25008660688327, + 124.77650539945358, + 110.41200699229772, + 128.38200813032248, + ) + ..cubicTo(112.762, 135.252, 114.50200000000001, 143.862, 116.232, 154.452) + ..close(); final Path intersect = bottom.applyOp(top, PathOp.intersect); // current revision of Skia makes this result in a quad verb getting used. diff --git a/packages/vector_graphics_compiler/test/path_test.dart b/packages/vector_graphics_compiler/test/path_test.dart index bcda67f6dd1..1305b5106d0 100644 --- a/packages/vector_graphics_compiler/test/path_test.dart +++ b/packages/vector_graphics_compiler/test/path_test.dart @@ -55,8 +55,8 @@ void main() { }); test('addRect', () { - final PathBuilder builder = - PathBuilder()..addRect(const Rect.fromLTRB(10, 10, 20, 20)); + final PathBuilder builder = PathBuilder() + ..addRect(const Rect.fromLTRB(10, 10, 20, 20)); expect( builder.toPath().toFlutterString(), @@ -70,10 +70,9 @@ void main() { }); test('addOval', () { - final PathBuilder builder = - PathBuilder() - ..addOval(const Rect.fromLTRB(10, 10, 20, 20)) - ..addOval(const Rect.fromLTRB(50, 50, 80, 70)); + final PathBuilder builder = PathBuilder() + ..addOval(const Rect.fromLTRB(10, 10, 20, 20)) + ..addOval(const Rect.fromLTRB(50, 50, 80, 70)); expect( builder.toPath().toFlutterString(), 'Path()\n' @@ -93,8 +92,8 @@ void main() { }); test('addRRect', () { - final PathBuilder builder = - PathBuilder()..addRRect(const Rect.fromLTRB(20, 20, 60, 60), 5, 5); + final PathBuilder builder = PathBuilder() + ..addRRect(const Rect.fromLTRB(20, 20, 60, 60), 5, 5); expect( builder.toPath().toFlutterString(), 'Path()\n' @@ -210,34 +209,31 @@ void main() { }); test('Compute path bounds with rect', () { - final PathBuilder builder = - PathBuilder() - ..addRect(const Rect.fromLTWH(5, 5, 95, 95)) - ..close(); + final PathBuilder builder = PathBuilder() + ..addRect(const Rect.fromLTWH(5, 5, 95, 95)) + ..close(); final Path path = builder.toPath(); expect(path.bounds(), const Rect.fromLTWH(5, 5, 95, 95)); }); test('Compute path bounds with lines', () { - final PathBuilder builder = - PathBuilder() - ..moveTo(0, 0) - ..lineTo(25, 0) - ..lineTo(25, 25) - ..lineTo(0, 25) - ..close(); + final PathBuilder builder = PathBuilder() + ..moveTo(0, 0) + ..lineTo(25, 0) + ..lineTo(25, 25) + ..lineTo(0, 25) + ..close(); final Path path = builder.toPath(); expect(path.bounds(), const Rect.fromLTWH(0, 0, 25, 25)); }); test('Compute path bounds with cubics', () { - final PathBuilder builder = - PathBuilder() - ..moveTo(0, 0) - ..cubicTo(10, 10, 20, 20, -10, -10) - ..close(); + final PathBuilder builder = PathBuilder() + ..moveTo(0, 0) + ..cubicTo(10, 10, 20, 20, -10, -10) + ..close(); final Path path = builder.toPath(); expect(path.bounds(), const Rect.fromLTRB(-10.0, -10.0, 20.0, 20.0)); diff --git a/packages/vector_graphics_compiler/test/resolver_test.dart b/packages/vector_graphics_compiler/test/resolver_test.dart index c38e375b3cc..ca332424565 100644 --- a/packages/vector_graphics_compiler/test/resolver_test.dart +++ b/packages/vector_graphics_compiler/test/resolver_test.dart @@ -51,8 +51,9 @@ void main() { final List nodes = queryChildren( resolvedNode, ); - final SaveLayerNode saveLayerNode = - queryChildren(resolvedNode).single; + final SaveLayerNode saveLayerNode = queryChildren( + resolvedNode, + ).single; expect(saveLayerNode.paint.fill!.color, const Color(0x7FFF0000)); @@ -172,8 +173,9 @@ void main() { ResolvingVisitor(), AffineMatrix.identity, ); - final ResolvedImageNode imageNode = - queryChildren(resolvedNode).single; + final ResolvedImageNode imageNode = queryChildren( + resolvedNode, + ).single; expect( imageNode.transform, const AffineMatrix(1.0, 0.0, 0.0, -1.0, 50.0, 50.0), diff --git a/packages/vector_graphics_compiler/test/test_svg_strings.dart b/packages/vector_graphics_compiler/test/test_svg_strings.dart index 327f1274db3..c84d40d0c05 100644 --- a/packages/vector_graphics_compiler/test/test_svg_strings.dart +++ b/packages/vector_graphics_compiler/test/test_svg_strings.dart @@ -1087,7 +1087,8 @@ const String missingRefs = ''' const String pathAndParent = ''' '''; -const String svgInlineImage = ''' +const String svgInlineImage = + ''' diff --git a/packages/video_player/video_player/CHANGELOG.md b/packages/video_player/video_player/CHANGELOG.md index 8593f312380..ea702cfe80f 100644 --- a/packages/video_player/video_player/CHANGELOG.md +++ b/packages/video_player/video_player/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. + ## 2.10.1 * Fixes a bug where the `VideoPlayer` widget and `VideoProgressIndicator` widget would stop updating after GlobalKey reparenting. diff --git a/packages/video_player/video_player/README.md b/packages/video_player/video_player/README.md index 261b68ba5c5..a5b2814c2c3 100644 --- a/packages/video_player/video_player/README.md +++ b/packages/video_player/video_player/README.md @@ -77,15 +77,16 @@ class _VideoAppState extends State { @override void initState() { super.initState(); - _controller = VideoPlayerController.networkUrl( - Uri.parse( - 'https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4', - ), - ) - ..initialize().then((_) { - // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed. - setState(() {}); - }); + _controller = + VideoPlayerController.networkUrl( + Uri.parse( + 'https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4', + ), + ) + ..initialize().then((_) { + // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed. + setState(() {}); + }); } @override @@ -94,13 +95,12 @@ class _VideoAppState extends State { title: 'Video Demo', home: Scaffold( body: Center( - child: - _controller.value.isInitialized - ? AspectRatio( - aspectRatio: _controller.value.aspectRatio, - child: VideoPlayer(_controller), - ) - : Container(), + child: _controller.value.isInitialized + ? AspectRatio( + aspectRatio: _controller.value.aspectRatio, + child: VideoPlayer(_controller), + ) + : Container(), ), floatingActionButton: FloatingActionButton( onPressed: () { diff --git a/packages/video_player/video_player/example/integration_test/controller_swap_test.dart b/packages/video_player/video_player/example/integration_test/controller_swap_test.dart index 2df68f07e2e..dc0f43681b2 100644 --- a/packages/video_player/video_player/example/integration_test/controller_swap_test.dart +++ b/packages/video_player/video_player/example/integration_test/controller_swap_test.dart @@ -18,8 +18,9 @@ void main() { 'can substitute one controller by another without crashing', (WidgetTester tester) async { // Use WebM for web to allow CI to use Chromium. - const String videoAssetKey = - kIsWeb ? 'assets/Butterfly-209.webm' : 'assets/Butterfly-209.mp4'; + const String videoAssetKey = kIsWeb + ? 'assets/Butterfly-209.webm' + : 'assets/Butterfly-209.mp4'; final VideoPlayerController controller = VideoPlayerController.asset( videoAssetKey, diff --git a/packages/video_player/video_player/example/integration_test/video_player_test.dart b/packages/video_player/video_player/example/integration_test/video_player_test.dart index 7ddf2404957..c4e46c1cb67 100644 --- a/packages/video_player/video_player/example/integration_test/video_player_test.dart +++ b/packages/video_player/video_player/example/integration_test/video_player_test.dart @@ -16,8 +16,9 @@ import 'package:video_player/video_player.dart'; const Duration _playDuration = Duration(seconds: 1); // Use WebM for web to allow CI to use Chromium. -const String _videoAssetKey = - kIsWeb ? 'assets/Butterfly-209.webm' : 'assets/Butterfly-209.mp4'; +const String _videoAssetKey = kIsWeb + ? 'assets/Butterfly-209.webm' + : 'assets/Butterfly-209.mp4'; // Returns the URL to load an asset from this example app as a network source. // @@ -213,19 +214,17 @@ void main() { child: Center( child: FutureBuilder( future: started(), - builder: ( - BuildContext context, - AsyncSnapshot snapshot, - ) { - if (snapshot.data ?? false) { - return AspectRatio( - aspectRatio: controller.value.aspectRatio, - child: VideoPlayer(controller), - ); - } else { - return const Text('waiting for video to load'); - } - }, + builder: + (BuildContext context, AsyncSnapshot snapshot) { + if (snapshot.data ?? false) { + return AspectRatio( + aspectRatio: controller.value.aspectRatio, + child: VideoPlayer(controller), + ); + } else { + return const Text('waiting for video to load'); + } + }, ), ), ), diff --git a/packages/video_player/video_player/example/lib/basic.dart b/packages/video_player/video_player/example/lib/basic.dart index f8ef6029ae6..3b9f3db665b 100644 --- a/packages/video_player/video_player/example/lib/basic.dart +++ b/packages/video_player/video_player/example/lib/basic.dart @@ -27,15 +27,16 @@ class _VideoAppState extends State { @override void initState() { super.initState(); - _controller = VideoPlayerController.networkUrl( - Uri.parse( - 'https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4', - ), - ) - ..initialize().then((_) { - // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed. - setState(() {}); - }); + _controller = + VideoPlayerController.networkUrl( + Uri.parse( + 'https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4', + ), + ) + ..initialize().then((_) { + // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed. + setState(() {}); + }); } @override @@ -44,13 +45,12 @@ class _VideoAppState extends State { title: 'Video Demo', home: Scaffold( body: Center( - child: - _controller.value.isInitialized - ? AspectRatio( - aspectRatio: _controller.value.aspectRatio, - child: VideoPlayer(_controller), - ) - : Container(), + child: _controller.value.isInitialized + ? AspectRatio( + aspectRatio: _controller.value.aspectRatio, + child: VideoPlayer(_controller), + ) + : Container(), ), floatingActionButton: FloatingActionButton( onPressed: () { diff --git a/packages/video_player/video_player/example/lib/main.dart b/packages/video_player/video_player/example/lib/main.dart index 1382af5d87d..d47a5abc601 100644 --- a/packages/video_player/video_player/example/lib/main.dart +++ b/packages/video_player/video_player/example/lib/main.dart @@ -50,17 +50,16 @@ class _App extends StatelessWidget { body: TabBarView( children: [ _ViewTypeTabBar( - builder: - (VideoViewType viewType) => _BumbleBeeRemoteVideo(viewType), + builder: (VideoViewType viewType) => + _BumbleBeeRemoteVideo(viewType), ), _ViewTypeTabBar( - builder: - (VideoViewType viewType) => _ButterFlyAssetVideo(viewType), + builder: (VideoViewType viewType) => + _ButterFlyAssetVideo(viewType), ), _ViewTypeTabBar( - builder: - (VideoViewType viewType) => - _ButterFlyAssetVideoInList(viewType), + builder: (VideoViewType viewType) => + _ButterFlyAssetVideoInList(viewType), ), ], ), @@ -381,20 +380,19 @@ class _ControlsOverlay extends StatelessWidget { AnimatedSwitcher( duration: const Duration(milliseconds: 50), reverseDuration: const Duration(milliseconds: 200), - child: - controller.value.isPlaying - ? const SizedBox.shrink() - : const ColoredBox( - color: Colors.black26, - child: Center( - child: Icon( - Icons.play_arrow, - color: Colors.white, - size: 100.0, - semanticLabel: 'Play', - ), + child: controller.value.isPlaying + ? const SizedBox.shrink() + : const ColoredBox( + color: Colors.black26, + child: Center( + child: Icon( + Icons.play_arrow, + color: Colors.white, + size: 100.0, + semanticLabel: 'Play', ), ), + ), ), GestureDetector( onTap: () { diff --git a/packages/video_player/video_player/example/pubspec.yaml b/packages/video_player/video_player/example/pubspec.yaml index 6c990c8b34f..339d5c010a4 100644 --- a/packages/video_player/video_player/example/pubspec.yaml +++ b/packages/video_player/video_player/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the video_player plugin. publish_to: none environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/video_player/video_player/lib/video_player.dart b/packages/video_player/video_player/lib/video_player.dart index c1a7bbccbd1..70460a96b5b 100644 --- a/packages/video_player/video_player/lib/video_player.dart +++ b/packages/video_player/video_player/lib/video_player.dart @@ -189,10 +189,9 @@ class VideoPlayerValue { volume: volume ?? this.volume, playbackSpeed: playbackSpeed ?? this.playbackSpeed, rotationCorrection: rotationCorrection ?? this.rotationCorrection, - errorDescription: - errorDescription != _defaultErrorDescription - ? errorDescription - : this.errorDescription, + errorDescription: errorDescription != _defaultErrorDescription + ? errorDescription + : this.errorDescription, isCompleted: isCompleted ?? this.isCompleted, ); } @@ -902,11 +901,11 @@ class _VideoPlayerState extends State { return _playerId == VideoPlayerController.kUninitializedPlayerId ? Container() : _VideoPlayerWithRotation( - rotation: widget.controller.value.rotationCorrection, - child: _videoPlayerPlatform.buildViewWithOptions( - VideoViewOptions(playerId: _playerId), - ), - ); + rotation: widget.controller.value.rotationCorrection, + child: _videoPlayerPlatform.buildViewWithOptions( + VideoViewOptions(playerId: _playerId), + ), + ); } } @@ -1114,13 +1113,12 @@ class _VideoProgressIndicatorState extends State { final int duration = controller.value.duration.inMilliseconds; final int position = controller.value.position.inMilliseconds; - final double maxBuffering = - duration == 0.0 - ? 0.0 - : controller.value.buffered - .map((DurationRange range) => range.end.inMilliseconds) - .fold(0, math.max) / - duration; + final double maxBuffering = duration == 0.0 + ? 0.0 + : controller.value.buffered + .map((DurationRange range) => range.end.inMilliseconds) + .fold(0, math.max) / + duration; progressIndicator = Stack( fit: StackFit.passthrough, children: [ diff --git a/packages/video_player/video_player/pubspec.yaml b/packages/video_player/video_player/pubspec.yaml index 956bbdd7180..a71e4532339 100644 --- a/packages/video_player/video_player/pubspec.yaml +++ b/packages/video_player/video_player/pubspec.yaml @@ -6,8 +6,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.10.1 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" flutter: plugin: diff --git a/packages/video_player/video_player/test/video_player_initialization_test.dart b/packages/video_player/video_player/test/video_player_initialization_test.dart index 394369380f0..0a71d1c6425 100644 --- a/packages/video_player/video_player/test/video_player_initialization_test.dart +++ b/packages/video_player/video_player/test/video_player_initialization_test.dart @@ -15,8 +15,8 @@ void main() { late FakeVideoPlayerPlatform fakeVideoPlayerPlatform; setUp(() { - VideoPlayerPlatform.instance = - fakeVideoPlayerPlatform = FakeVideoPlayerPlatform(); + VideoPlayerPlatform.instance = fakeVideoPlayerPlatform = + FakeVideoPlayerPlatform(); }); test('plugin initialized', () async { diff --git a/packages/video_player/video_player_platform_interface/CHANGELOG.md b/packages/video_player/video_player_platform_interface/CHANGELOG.md index 6d7fd75aa7a..a0e403be5dc 100644 --- a/packages/video_player/video_player_platform_interface/CHANGELOG.md +++ b/packages/video_player/video_player_platform_interface/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. + ## 6.6.0 * Adds `VideoAudioTrack` class and `getAudioTracks()`, `selectAudioTrack()`, `isAudioTrackSupportAvailable()` methods for audio track management. diff --git a/packages/video_player/video_player_platform_interface/pubspec.yaml b/packages/video_player/video_player_platform_interface/pubspec.yaml index d310fee9afb..2d93a65e8ad 100644 --- a/packages/video_player/video_player_platform_interface/pubspec.yaml +++ b/packages/video_player/video_player_platform_interface/pubspec.yaml @@ -7,8 +7,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 6.6.0 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/video_player/video_player_web/CHANGELOG.md b/packages/video_player/video_player_web/CHANGELOG.md index 83c26791acd..2f383e86f2d 100644 --- a/packages/video_player/video_player_web/CHANGELOG.md +++ b/packages/video_player/video_player_web/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 2.4.0 diff --git a/packages/video_player/video_player_web/example/integration_test/video_player_test.dart b/packages/video_player/video_player_web/example/integration_test/video_player_test.dart index c183c6c076e..2e7c1a44f50 100644 --- a/packages/video_player/video_player_web/example/integration_test/video_player_test.dart +++ b/packages/video_player/video_player_web/example/integration_test/video_player_test.dart @@ -24,19 +24,17 @@ void main() { setUp(() { // Never set "src" on the video, so this test doesn't hit the network! - video = - web.HTMLVideoElement() - ..controls = true - ..playsInline = false; + video = web.HTMLVideoElement() + ..controls = true + ..playsInline = false; }); testWidgets('initialize() calls load', (WidgetTester _) async { bool loadCalled = false; - video['load'] = - () { - loadCalled = true; - }.toJS; + video['load'] = () { + loadCalled = true; + }.toJS; VideoPlayer(videoElement: video).initialize(); @@ -193,17 +191,15 @@ void main() { WidgetTester tester, ) async { // Take all the "buffering" events that we see during the next few seconds - final Future> stream = - timedStream - .where( - (VideoEvent event) => - bufferingEvents.contains(event.eventType), - ) - .map( - (VideoEvent event) => - event.eventType == VideoEventType.bufferingStart, - ) - .toList(); + final Future> stream = timedStream + .where( + (VideoEvent event) => bufferingEvents.contains(event.eventType), + ) + .map( + (VideoEvent event) => + event.eventType == VideoEventType.bufferingStart, + ) + .toList(); // Simulate some events coming from the player... player.setBuffering(true); @@ -226,17 +222,15 @@ void main() { WidgetTester tester, ) async { // Take all the "buffering" events that we see during the next few seconds - final Future> stream = - timedStream - .where( - (VideoEvent event) => - bufferingEvents.contains(event.eventType), - ) - .map( - (VideoEvent event) => - event.eventType == VideoEventType.bufferingStart, - ) - .toList(); + final Future> stream = timedStream + .where( + (VideoEvent event) => bufferingEvents.contains(event.eventType), + ) + .map( + (VideoEvent event) => + event.eventType == VideoEventType.bufferingStart, + ) + .toList(); player.setBuffering(true); @@ -253,17 +247,15 @@ void main() { WidgetTester tester, ) async { // Take all the "buffering" events that we see during the next few seconds - final Future> stream = - timedStream - .where( - (VideoEvent event) => - bufferingEvents.contains(event.eventType), - ) - .map( - (VideoEvent event) => - event.eventType == VideoEventType.bufferingStart, - ) - .toList(); + final Future> stream = timedStream + .where( + (VideoEvent event) => bufferingEvents.contains(event.eventType), + ) + .map( + (VideoEvent event) => + event.eventType == VideoEventType.bufferingStart, + ) + .toList(); player.setBuffering(true); @@ -285,13 +277,12 @@ void main() { video.dispatchEvent(web.Event('canplay')); // Take all the "initialized" events that we see during the next few seconds - final Future> stream = - timedStream - .where( - (VideoEvent event) => - event.eventType == VideoEventType.initialized, - ) - .toList(); + final Future> stream = timedStream + .where( + (VideoEvent event) => + event.eventType == VideoEventType.initialized, + ) + .toList(); video.dispatchEvent(web.Event('canplay')); video.dispatchEvent(web.Event('canplay')); @@ -309,13 +300,12 @@ void main() { video.dispatchEvent(web.Event('loadedmetadata')); video.dispatchEvent(web.Event('loadedmetadata')); - final Future> stream = - timedStream - .where( - (VideoEvent event) => - event.eventType == VideoEventType.initialized, - ) - .toList(); + final Future> stream = timedStream + .where( + (VideoEvent event) => + event.eventType == VideoEventType.initialized, + ) + .toList(); final List events = await stream; @@ -328,13 +318,12 @@ void main() { video.dispatchEvent(web.Event('loadeddata')); video.dispatchEvent(web.Event('loadeddata')); - final Future> stream = - timedStream - .where( - (VideoEvent event) => - event.eventType == VideoEventType.initialized, - ) - .toList(); + final Future> stream = timedStream + .where( + (VideoEvent event) => + event.eventType == VideoEventType.initialized, + ) + .toList(); final List events = await stream; @@ -346,13 +335,12 @@ void main() { setInfinityDuration(video); expect(video.duration.isInfinite, isTrue); - final Future> stream = - timedStream - .where( - (VideoEvent event) => - event.eventType == VideoEventType.initialized, - ) - .toList(); + final Future> stream = timedStream + .where( + (VideoEvent event) => + event.eventType == VideoEventType.initialized, + ) + .toList(); video.dispatchEvent(web.Event('canplay')); diff --git a/packages/video_player/video_player_web/example/integration_test/video_player_web_test.dart b/packages/video_player/video_player_web/example/integration_test/video_player_web_test.dart index dc70f9f35b6..f5c914e94cb 100644 --- a/packages/video_player/video_player_web/example/integration_test/video_player_web_test.dart +++ b/packages/video_player/video_player_web/example/integration_test/video_player_web_test.dart @@ -122,8 +122,8 @@ void main() { testWidgets('throws PlatformException when playing bad media', ( WidgetTester tester, ) async { - final int videoPlayerId = - (await VideoPlayerPlatform.instance.createWithOptions( + final int videoPlayerId = (await VideoPlayerPlatform.instance + .createWithOptions( VideoCreationOptions( dataSource: DataSource( sourceType: DataSourceType.network, @@ -210,15 +210,14 @@ void main() { final Stream eventStream = VideoPlayerPlatform.instance .videoEventsFor(videoPlayerId); - final Future> stream = - eventStream - .timeout( - const Duration(seconds: 2), - onTimeout: (EventSink sink) { - sink.close(); - }, - ) - .toList(); + final Future> stream = eventStream + .timeout( + const Duration(seconds: 2), + onTimeout: (EventSink sink) { + sink.close(); + }, + ) + .toList(); await VideoPlayerPlatform.instance.setVolume(videoPlayerId, 0); await VideoPlayerPlatform.instance.play(videoPlayerId); @@ -253,15 +252,14 @@ void main() { final Stream eventStream = VideoPlayerPlatform.instance .videoEventsFor(videoPlayerId); - final Future> stream = - eventStream - .timeout( - const Duration(seconds: 2), - onTimeout: (EventSink sink) { - sink.close(); - }, - ) - .toList(); + final Future> stream = eventStream + .timeout( + const Duration(seconds: 2), + onTimeout: (EventSink sink) { + sink.close(); + }, + ) + .toList(); await VideoPlayerPlatform.instance.setVolume(videoPlayerId, 0); await VideoPlayerPlatform.instance.play(videoPlayerId); diff --git a/packages/video_player/video_player_web/example/pubspec.yaml b/packages/video_player/video_player_web/example/pubspec.yaml index e3bce694990..92f965e988d 100644 --- a/packages/video_player/video_player_web/example/pubspec.yaml +++ b/packages/video_player/video_player_web/example/pubspec.yaml @@ -2,8 +2,8 @@ name: video_player_for_web_integration_tests publish_to: none environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: flutter: diff --git a/packages/video_player/video_player_web/lib/src/video_player.dart b/packages/video_player/video_player_web/lib/src/video_player.dart index af7dfcd5920..d3ee51e3910 100644 --- a/packages/video_player/video_player_web/lib/src/video_player.dart +++ b/packages/video_player/video_player_web/lib/src/video_player.dart @@ -313,13 +313,12 @@ class VideoPlayer { _videoElement.duration, ); - final Size? size = - _videoElement.videoHeight.isFinite - ? Size( - _videoElement.videoWidth.toDouble(), - _videoElement.videoHeight.toDouble(), - ) - : null; + final Size? size = _videoElement.videoHeight.isFinite + ? Size( + _videoElement.videoWidth.toDouble(), + _videoElement.videoHeight.toDouble(), + ) + : null; _eventController.add( VideoEvent( @@ -340,10 +339,9 @@ class VideoPlayer { _isBuffering = buffering; _eventController.add( VideoEvent( - eventType: - _isBuffering - ? VideoEventType.bufferingStart - : VideoEventType.bufferingEnd, + eventType: _isBuffering + ? VideoEventType.bufferingStart + : VideoEventType.bufferingEnd, ), ); } diff --git a/packages/video_player/video_player_web/lib/video_player_web.dart b/packages/video_player/video_player_web/lib/video_player_web.dart index a7061b6652a..279e1298907 100644 --- a/packages/video_player/video_player_web/lib/video_player_web.dart +++ b/packages/video_player/video_player_web/lib/video_player_web.dart @@ -90,12 +90,11 @@ class VideoPlayerPlugin extends VideoPlayerPlatform { ); } - final web.HTMLVideoElement videoElement = - web.HTMLVideoElement() - ..id = 'videoElement-$playerId' - ..style.border = 'none' - ..style.height = '100%' - ..style.width = '100%'; + final web.HTMLVideoElement videoElement = web.HTMLVideoElement() + ..id = 'videoElement-$playerId' + ..style.border = 'none' + ..style.height = '100%' + ..style.width = '100%'; // TODO(hterkelsen): Use initialization parameters once they are available ui_web.platformViewRegistry.registerViewFactory( diff --git a/packages/video_player/video_player_web/pubspec.yaml b/packages/video_player/video_player_web/pubspec.yaml index ca36ffe35ee..39148c8fd3c 100644 --- a/packages/video_player/video_player_web/pubspec.yaml +++ b/packages/video_player/video_player_web/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.4.0 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" flutter: plugin: diff --git a/packages/web_benchmarks/CHANGELOG.md b/packages/web_benchmarks/CHANGELOG.md index 3a529e23eea..f9c6a380aed 100644 --- a/packages/web_benchmarks/CHANGELOG.md +++ b/packages/web_benchmarks/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. ## 4.0.0 diff --git a/packages/web_benchmarks/lib/analysis.dart b/packages/web_benchmarks/lib/analysis.dart index ca6a5c8d1c4..73edaf62fb4 100644 --- a/packages/web_benchmarks/lib/analysis.dart +++ b/packages/web_benchmarks/lib/analysis.dart @@ -47,19 +47,18 @@ BenchmarkResults computeDelta( for (final String benchmarkName in test.scores.keys) { final List testScores = test.scores[benchmarkName]!; final List? baselineScores = baseline.scores[benchmarkName]; - delta[benchmarkName] = - testScores.map((BenchmarkScore testScore) { - final BenchmarkScore? baselineScore = baselineScores - ?.firstWhereOrNull( - (BenchmarkScore s) => s.metric == testScore.metric, - ); - return testScore._copyWith( - delta: - baselineScore == null - ? null - : (testScore.value - baselineScore.value).toDouble(), - ); - }).toList(); + delta[benchmarkName] = testScores.map(( + BenchmarkScore testScore, + ) { + final BenchmarkScore? baselineScore = baselineScores?.firstWhereOrNull( + (BenchmarkScore s) => s.metric == testScore.metric, + ); + return testScore._copyWith( + delta: baselineScore == null + ? null + : (testScore.value - baselineScore.value).toDouble(), + ); + }).toList(); } return BenchmarkResults(delta); } @@ -93,26 +92,24 @@ extension _AnalysisExtension on BenchmarkResults { } final List scoresForBenchmark = scores[benchmark]!; - sum[benchmark] = - scoresForBenchmark.map((BenchmarkScore score) { - // Look up this score in the [matchingBenchmark] from [other]. - final BenchmarkScore? matchingScore = matchingBenchmark - .firstWhereOrNull( - (BenchmarkScore s) => s.metric == score.metric, - ); - if (matchingScore == null && throwExceptionOnMismatch) { - throw Exception( - 'Cannot sum benchmarks because benchmark "$benchmark" is missing ' - 'a score for metric ${score.metric}.', - ); - } - return score._copyWith( - value: - matchingScore == null - ? score.value - : score.value + matchingScore.value, - ); - }).toList(); + sum[benchmark] = scoresForBenchmark.map(( + BenchmarkScore score, + ) { + // Look up this score in the [matchingBenchmark] from [other]. + final BenchmarkScore? matchingScore = matchingBenchmark + .firstWhereOrNull((BenchmarkScore s) => s.metric == score.metric); + if (matchingScore == null && throwExceptionOnMismatch) { + throw Exception( + 'Cannot sum benchmarks because benchmark "$benchmark" is missing ' + 'a score for metric ${score.metric}.', + ); + } + return score._copyWith( + value: matchingScore == null + ? score.value + : score.value + matchingScore.value, + ); + }).toList(); } return BenchmarkResults(sum); } diff --git a/packages/web_benchmarks/lib/client.dart b/packages/web_benchmarks/lib/client.dart index 1bb486703da..d9d60e30501 100644 --- a/packages/web_benchmarks/lib/client.dart +++ b/packages/web_benchmarks/lib/client.dart @@ -68,14 +68,13 @@ Future runBenchmarks( final Uri currentUri = Uri.parse(window.location.href); // Create a new URI with the parsed value of [benchmarkPath] to ensure the // benchmark app is reloaded with the proper configuration. - final String newUri = - Uri.parse(benchmarkPath) - .replace( - scheme: currentUri.scheme, - host: currentUri.host, - port: currentUri.port, - ) - .toString(); + final String newUri = Uri.parse(benchmarkPath) + .replace( + scheme: currentUri.scheme, + host: currentUri.host, + port: currentUri.port, + ) + .toString(); // Reloading the window will trigger the next benchmark to run. await _client.printToConsole( @@ -95,15 +94,14 @@ Future _runBenchmark(String? benchmarkName) async { await runZoned>( () async { final Recorder recorder = recorderFactory(); - final Runner runner = - recorder.isTracingEnabled && !_client.isInManualMode - ? Runner( - recorder: recorder, - setUpAllDidRun: - () => _client.startPerformanceTracing(benchmarkName), - tearDownAllWillRun: _client.stopPerformanceTracing, - ) - : Runner(recorder: recorder); + final Runner runner = recorder.isTracingEnabled && !_client.isInManualMode + ? Runner( + recorder: recorder, + setUpAllDidRun: () => + _client.startPerformanceTracing(benchmarkName), + tearDownAllWillRun: _client.stopPerformanceTracing, + ) + : Runner(recorder: recorder); final Profile profile = await runner.run(); if (!_client.isInManualMode) { @@ -121,20 +119,21 @@ Future _runBenchmark(String? benchmarkName) async { await _client.printToConsole(line); } }, - handleUncaughtError: ( - Zone self, - ZoneDelegate parent, - Zone zone, - Object error, - StackTrace stackTrace, - ) async { - if (_client.isInManualMode) { - parent.print(zone, '[$benchmarkName] $error, $stackTrace'); - parent.handleUncaughtError(zone, error, stackTrace); - } else { - await _client.reportError(error, stackTrace); - } - }, + handleUncaughtError: + ( + Zone self, + ZoneDelegate parent, + Zone zone, + Object error, + StackTrace stackTrace, + ) async { + if (_client.isInManualMode) { + parent.print(zone, '[$benchmarkName] $error, $stackTrace'); + parent.handleUncaughtError(zone, error, stackTrace); + } else { + await _client.reportError(error, stackTrace); + } + }, ), ); } diff --git a/packages/web_benchmarks/lib/src/browser.dart b/packages/web_benchmarks/lib/src/browser.dart index 30994bfac51..137d7b6fccf 100644 --- a/packages/web_benchmarks/lib/src/browser.dart +++ b/packages/web_benchmarks/lib/src/browser.dart @@ -376,10 +376,9 @@ class BlinkTraceSummary { final int tabPid = firstMeasuredFrameEvent.pid; // Filter out data from unrelated processes - events = - events - .where((BlinkTraceEvent element) => element.pid == tabPid) - .toList(); + events = events + .where((BlinkTraceEvent element) => element.pid == tabPid) + .toList(); // Extract frame data. final List frames = []; diff --git a/packages/web_benchmarks/lib/src/computations.dart b/packages/web_benchmarks/lib/src/computations.dart index 467c70fb3b9..605fe93817f 100644 --- a/packages/web_benchmarks/lib/src/computations.dart +++ b/packages/web_benchmarks/lib/src/computations.dart @@ -101,16 +101,18 @@ class Timeseries { name, cleanValues, ); - final double noise = - cleanAverage > 0.0 ? standardDeviation / cleanAverage : 0.0; + final double noise = cleanAverage > 0.0 + ? standardDeviation / cleanAverage + : 0.0; // Compute outlier average. If there are no outliers the outlier average is // the same as clean value average. In other words, in a perfect benchmark // with no noise the difference between average and outlier average is zero, // which the best possible outcome. Noise produces a positive difference // between the two. - final double outlierAverage = - outliers.isNotEmpty ? _computeAverage(name, outliers) : cleanAverage; + final double outlierAverage = outliers.isNotEmpty + ? _computeAverage(name, outliers) + : cleanAverage; // Compute percentile values (e.g. p50, p90, p95). final Map percentiles = computePercentiles( @@ -235,10 +237,9 @@ class TimeseriesStats { /// This is a measure of performance consistency. The higher this number the /// worse is jank when it happens. Smaller is better, with 1.0 being the /// perfect score. If [average] is zero, this value defaults to 1.0. - double get outlierRatio => - average > 0.0 - ? outlierAverage / average - : 1.0; // this can only happen in perfect benchmark that reports only zeros + double get outlierRatio => average > 0.0 + ? outlierAverage / average + : 1.0; // this can only happen in perfect benchmark that reports only zeros @override String toString() { diff --git a/packages/web_benchmarks/lib/src/metrics.dart b/packages/web_benchmarks/lib/src/metrics.dart index 0f47d2a8914..34eaf8dd452 100644 --- a/packages/web_benchmarks/lib/src/metrics.dart +++ b/packages/web_benchmarks/lib/src/metrics.dart @@ -137,10 +137,9 @@ final class PercentileMetricComputation extends BenchmarkMetricComputation { ]; /// The percentile values as doubles computed for each benchmark metric. - static List percentilesAsDoubles = - PercentileMetricComputation.values - .map((PercentileMetricComputation value) => value.percentile) - .toList(); + static List percentilesAsDoubles = PercentileMetricComputation.values + .map((PercentileMetricComputation value) => value.percentile) + .toList(); } /// The list of expected benchmark metrics for the current compilation mode, as diff --git a/packages/web_benchmarks/lib/src/recorder.dart b/packages/web_benchmarks/lib/src/recorder.dart index 0581e4a653e..c4667762373 100644 --- a/packages/web_benchmarks/lib/src/recorder.dart +++ b/packages/web_benchmarks/lib/src/recorder.dart @@ -405,8 +405,10 @@ abstract class WidgetRecorder extends Recorder implements FrameRecorder { @override Future run() async { _runCompleter = Completer(); - final Profile localProfile = - profile = Profile(name: name, useCustomWarmUp: useCustomWarmUp); + final Profile localProfile = profile = Profile( + name: name, + useCustomWarmUp: useCustomWarmUp, + ); final _RecordingWidgetsBinding binding = _RecordingWidgetsBinding.ensureInitialized(); final Widget widget = createWidget(); diff --git a/packages/web_benchmarks/lib/src/runner.dart b/packages/web_benchmarks/lib/src/runner.dart index 2cc75985bba..a57762c5182 100644 --- a/packages/web_benchmarks/lib/src/runner.dart +++ b/packages/web_benchmarks/lib/src/runner.dart @@ -113,10 +113,9 @@ class BenchmarkServer { /// The default value is [defaultInitialPath]. final String benchmarkPath; - String get _benchmarkAppUrl => - Uri.parse(benchmarkPath) - .replace(scheme: 'http', host: 'localhost', port: benchmarkServerPort) - .toString(); + String get _benchmarkAppUrl => Uri.parse(benchmarkPath) + .replace(scheme: 'http', host: 'localhost', port: benchmarkServerPort) + .toString(); /// Builds and serves the benchmark app, and collects benchmark results. Future run() async { @@ -143,12 +142,11 @@ class BenchmarkServer { entryPoint, ], workingDirectory: benchmarkAppDirectory.path); - final int buildTime = - Duration( - milliseconds: - DateTime.now().millisecondsSinceEpoch - - startTime.millisecondsSinceEpoch, - ).inSeconds; + final int buildTime = Duration( + milliseconds: + DateTime.now().millisecondsSinceEpoch - + startTime.millisecondsSinceEpoch, + ).inSeconds; print('Build took ${buildTime}s to complete.'); if (buildResult.exitCode != 0) { @@ -322,10 +320,9 @@ class BenchmarkServer { benchmarkAppDirectory.path, '.dart_tool', ); - final String userDataDir = - io.Directory( - dartToolDirectory, - ).createTempSync('chrome_user_data_').path; + final String userDataDir = io.Directory( + dartToolDirectory, + ).createTempSync('chrome_user_data_').path; final ChromeOptions options = ChromeOptions( url: _benchmarkAppUrl, diff --git a/packages/web_benchmarks/pubspec.yaml b/packages/web_benchmarks/pubspec.yaml index e842a9b9f11..6912d4a1bbe 100644 --- a/packages/web_benchmarks/pubspec.yaml +++ b/packages/web_benchmarks/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 4.0.0 environment: - sdk: ^3.7.0 - flutter: ">=3.29.0" + sdk: ^3.8.0 + flutter: ">=3.32.0" dependencies: collection: ^1.18.0 diff --git a/packages/web_benchmarks/testing/test_app/benchmark/test_infra/client/app_client.dart b/packages/web_benchmarks/testing/test_app/benchmark/test_infra/client/app_client.dart index 6729a3a26c3..80c0742a4a2 100644 --- a/packages/web_benchmarks/testing/test_app/benchmark/test_infra/client/app_client.dart +++ b/packages/web_benchmarks/testing/test_app/benchmark/test_infra/client/app_client.dart @@ -9,11 +9,11 @@ import '../recorder.dart'; Future main() async { await runBenchmarks({ - BenchmarkName.appNavigate.name: - () => TestAppRecorder(benchmark: BenchmarkName.appNavigate), - BenchmarkName.appScroll.name: - () => TestAppRecorder(benchmark: BenchmarkName.appScroll), - BenchmarkName.appTap.name: - () => TestAppRecorder(benchmark: BenchmarkName.appTap), + BenchmarkName.appNavigate.name: () => + TestAppRecorder(benchmark: BenchmarkName.appNavigate), + BenchmarkName.appScroll.name: () => + TestAppRecorder(benchmark: BenchmarkName.appScroll), + BenchmarkName.appTap.name: () => + TestAppRecorder(benchmark: BenchmarkName.appTap), }); } diff --git a/packages/web_benchmarks/testing/test_app/benchmark/test_infra/client/simple_benchmark_path_client.dart b/packages/web_benchmarks/testing/test_app/benchmark/test_infra/client/simple_benchmark_path_client.dart index 2bb2a6f7ee5..2940758a979 100644 --- a/packages/web_benchmarks/testing/test_app/benchmark/test_infra/client/simple_benchmark_path_client.dart +++ b/packages/web_benchmarks/testing/test_app/benchmark/test_infra/client/simple_benchmark_path_client.dart @@ -9,8 +9,7 @@ import '../recorder.dart'; Future main() async { await runBenchmarks({ - BenchmarkName.simpleBenchmarkPathCheck.name: - () => - TestAppRecorder(benchmark: BenchmarkName.simpleBenchmarkPathCheck), + BenchmarkName.simpleBenchmarkPathCheck.name: () => + TestAppRecorder(benchmark: BenchmarkName.simpleBenchmarkPathCheck), }, benchmarkPath: testBenchmarkPath); } diff --git a/packages/web_benchmarks/testing/test_app/benchmark/test_infra/client/simple_compilation_client.dart b/packages/web_benchmarks/testing/test_app/benchmark/test_infra/client/simple_compilation_client.dart index e9a6c5e3885..1e17f39e862 100644 --- a/packages/web_benchmarks/testing/test_app/benchmark/test_infra/client/simple_compilation_client.dart +++ b/packages/web_benchmarks/testing/test_app/benchmark/test_infra/client/simple_compilation_client.dart @@ -9,7 +9,7 @@ import '../recorder.dart'; Future main() async { await runBenchmarks({ - BenchmarkName.simpleCompilationCheck.name: - () => TestAppRecorder(benchmark: BenchmarkName.simpleCompilationCheck), + BenchmarkName.simpleCompilationCheck.name: () => + TestAppRecorder(benchmark: BenchmarkName.simpleCompilationCheck), }); } diff --git a/packages/web_benchmarks/testing/test_app/benchmark/web_benchmarks_test.dart b/packages/web_benchmarks/testing/test_app/benchmark/web_benchmarks_test.dart index 8868fbf1b99..fd00b06ab65 100644 --- a/packages/web_benchmarks/testing/test_app/benchmark/web_benchmarks_test.dart +++ b/packages/web_benchmarks/testing/test_app/benchmark/web_benchmarks_test.dart @@ -84,10 +84,9 @@ Future _runBenchmarks({ compilationOptions: compilationOptions, ); - final List expectedMetrics = - expectedBenchmarkMetrics( - useWasm: compilationOptions.useWasm, - ).map((BenchmarkMetric metric) => metric.label).toList(); + final List expectedMetrics = expectedBenchmarkMetrics( + useWasm: compilationOptions.useWasm, + ).map((BenchmarkMetric metric) => metric.label).toList(); for (final String benchmarkName in benchmarkNames) { for (final String metricName in expectedMetrics) { diff --git a/packages/web_benchmarks/testing/test_app/pubspec.yaml b/packages/web_benchmarks/testing/test_app/pubspec.yaml index 8b8bdc3aacf..76e10f0514b 100644 --- a/packages/web_benchmarks/testing/test_app/pubspec.yaml +++ b/packages/web_benchmarks/testing/test_app/pubspec.yaml @@ -6,7 +6,7 @@ publish_to: 'none' version: 1.0.0+1 environment: - sdk: ^3.7.0 + sdk: ^3.8.0 dependencies: flutter: diff --git a/packages/web_benchmarks/tool/run_tests.dart b/packages/web_benchmarks/tool/run_tests.dart index 047d8eebe14..df42ceecb59 100644 --- a/packages/web_benchmarks/tool/run_tests.dart +++ b/packages/web_benchmarks/tool/run_tests.dart @@ -22,8 +22,9 @@ Future main(List args) async { exit(0); } - final Directory packageDir = - Directory(p.dirname(Platform.script.path)).parent; + final Directory packageDir = Directory( + p.dirname(Platform.script.path), + ).parent; final String testingAppDirPath = p.join( packageDir.path, 'testing', diff --git a/packages/webview_flutter/webview_flutter/CHANGELOG.md b/packages/webview_flutter/webview_flutter/CHANGELOG.md index fad345bad30..305b5adc87c 100644 --- a/packages/webview_flutter/webview_flutter/CHANGELOG.md +++ b/packages/webview_flutter/webview_flutter/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.29/Dart 3.7. +* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. * Updates README to reflect that only Android API 24+ is supported. ## 4.13.0 diff --git a/packages/webview_flutter/webview_flutter/README.md b/packages/webview_flutter/webview_flutter/README.md index 5c0d2b8aaf3..267519d3e81 100644 --- a/packages/webview_flutter/webview_flutter/README.md +++ b/packages/webview_flutter/webview_flutter/README.md @@ -21,27 +21,26 @@ You can now display a WebView by: ```dart -controller = - WebViewController() - ..setJavaScriptMode(JavaScriptMode.unrestricted) - ..setNavigationDelegate( - NavigationDelegate( - onProgress: (int progress) { - // Update loading bar. - }, - onPageStarted: (String url) {}, - onPageFinished: (String url) {}, - onHttpError: (HttpResponseError error) {}, - onWebResourceError: (WebResourceError error) {}, - onNavigationRequest: (NavigationRequest request) { - if (request.url.startsWith('https://www.youtube.com/')) { - return NavigationDecision.prevent; - } - return NavigationDecision.navigate; - }, - ), - ) - ..loadRequest(Uri.parse('https://flutter.dev')); +controller = WebViewController() + ..setJavaScriptMode(JavaScriptMode.unrestricted) + ..setNavigationDelegate( + NavigationDelegate( + onProgress: (int progress) { + // Update loading bar. + }, + onPageStarted: (String url) {}, + onPageFinished: (String url) {}, + onHttpError: (HttpResponseError error) {}, + onWebResourceError: (WebResourceError error) {}, + onNavigationRequest: (NavigationRequest request) { + if (request.url.startsWith('https://www.youtube.com/')) { + return NavigationDecision.prevent; + } + return NavigationDecision.navigate; + }, + ), + ) + ..loadRequest(Uri.parse('https://flutter.dev')); ``` 2. Passing the controller to a [WebViewWidget](https://pub.dev/documentation/webview_flutter/latest/webview_flutter/WebViewWidget-class.html). diff --git a/packages/webview_flutter/webview_flutter/example/integration_test/webview_flutter_test.dart b/packages/webview_flutter/webview_flutter/example/integration_test/webview_flutter_test.dart index 4380c7f662a..aebfaaff445 100644 --- a/packages/webview_flutter/webview_flutter/example/integration_test/webview_flutter_test.dart +++ b/packages/webview_flutter/webview_flutter/example/integration_test/webview_flutter_test.dart @@ -355,7 +355,8 @@ Future main() async { final String base64AudioData = base64Encode( Uint8List.view(audioData.buffer), ); - final String audioTest = ''' + final String audioTest = + ''' Audio auto play